作者:demigodliu
链接:leetcode-cn.com/problems/va…
来源:力扣(LeetCode)
解题思路
- 有效括号字符串的长度,一定是偶数!
- 右括号前面,必须是相对应的左括号,才能抵消!
- 右括号前面,不是对应的左括号,那么该字符串,一定不是有效的括号!
图解
示例代码
let isValid = function(s) {
let stack = [], length = s.length;
if(length % 2) return false;
for(let item of s){
switch(item){
case "{":
case "[":
case "(":
stack.push(item);
break;
case "}":
if(stack.pop() !== "{") return false;
break;
case "]":
if(stack.pop() !== "[") return false;
break;
case ")":
if(stack.pop() !== "(") return false;
break;
}
}
return !stack.length;
};