const isValid = function (s) {
const stack = [];
for (let i = 0; i < s.length; i++) {
let c = s[i];
switch (c) {
// 左括号入栈,即将与左括号匹配的右括号入栈
case "(":
stack.push(")");
break;
case "[":
stack.push("]");
break;
case "{":
stack.push("}");
break;
// 右括号出栈, 比较栈顶元素和当前元素是否匹配
default:
if (c !== stack.pop()) {
return false;
}
}
}
// 遍历完,只要栈不为空,那么一定不匹配
return stack.length === 0;
};
// isValid("()[]{}")
isValid("([)]");
标签:case,匹配,isValid,break,括号,算法,stack
From: https://www.cnblogs.com/zhuoss/p/16900622.html