使用Map保存左右括号,遍历字符串,遇到左括号入栈,遇到右括号出栈进行比较,如果不匹配则返回false。最后看栈里面是否还有元素,如果有返回false否则饭返回true。
var isValid = function(s) {
if(s.length%2!==0)return false;
let map = new Map([[')','('],[']','['],['}','{']]);
let stack = [];
for(let i=0;i<s.length;i++){
const temp = map.get(s[i]);
if(temp===undefined){
stack.push(s[i]);
}else{
let pop = stack.pop();
if(temp!==pop)return false;
}
}
if(stack.length!==0)return false;
return true;
};