题目
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
示例 6:
输入:s = "([}}])"
输出:false
题解
栈
按照右括号出现的顺序,只存左括号的栈,栈顶对应‘消消乐’,直到栈内无左括号,即s为有效括号。
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack = [];
const n = s.length;
if(n%2 === 1){
return false
}
const parenthesesaMap = new Map([
[')', '('],
[']', '['],
['}', '{']
]);
for(let i of s){
if(parenthesesaMap.has(i)){
if(!!stack.length && stack[stack.length-1] === parenthesesaMap.get(i)){
stack.pop();
} else return false
} else stack.push(i)
}
return !stack.length;
};