判断一个包含括号的字符串是否有效,可以使用栈来解决这个问题。这个问题可以通过以下步骤来实现:
function isValid(s) {
const stack = [];
const map = {
'(': ')',
'{': '}',
'[': ']'
};
for (let char of s) {
if (map[char]) {
// If the character is a left bracket
stack.push(char);
} else {
// If the character is a right bracket
const topElement = stack.pop();
if (map[topElement] !== char) {
return false;
}
}
}
return stack.length === 0;
}
// 示例
console.log(isValid("()")); // true
console.log(isValid("()[]{}")); // true
console.log(isValid("(]")); // false
console.log(isValid("([)]")); // false
console.log(isValid("{[]}")); // true
stack 和一个括号匹配的映射 map。s 中的每个字符 char:
char 是左括号(即存在于 map 的键中),则将其推入栈 stack。char 是右括号:
stack 中弹出栈顶元素 topElement。map 中 topElement 对应的值是否等于 char。如果不等,则返回 false。stack 是否为空。如果为空,则返回 true;否则返回 false。