35 lines
1.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {string} s
* @return {boolean}
*/
const isValid = function (s) {
};
/*
题目所给的测试用例只包含'('')''{''}''['']'这些字符,如果是一个有效字符则说明它一定是一对一对的出现
也就是说s的长度是偶数如果是奇数就一定存在一个括号没有闭合倘若是偶数个我们需要在遇到右括号时检查它的前一个
括号是否是对应的左括号,如果是的话,则表明这是一对合理的括号,之后检查后一个括号,以次类推。
*/
function f1(s) {
// 如果长度不是偶数,一定不能正常闭合
if (s.length % 2 !== 0) return false;
// 括号的映射表
const map = new Map([
[')', '('],
[']', '['],
['}', '{'],
]);
const stack = []; // 利用栈结构来检查括号是否整除闭合
for (const brack of s) {
if (map.has(brack)) {
// 如果栈为空或者栈顶括号不是对应的括号表明不能正常闭合返回false
if (!stack.length || stack[stack.length - 1] !== map.get(brack)) return false;
stack.pop();// 如果正常闭合,从栈中去掉这个左括号
} else {
stack.push(brack);
}
}
return !stack.length;
}