给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
思路:使用js中数组的栈方法,左括号入栈,右括号匹配后出栈。匹配过程中,如果最近入栈的括号与正在判断的右括号不是一对,则返回false,如果字符串遍历结束,但栈中还有剩余元素,一定是左括号的数量多余右括号,返回false。
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const n = s.length;
let stack = [];
let i = 0;
if(s.length < 2) return false;
while(i < n){
let temp = s.charAt(i);
if(temp === '(' || temp === '{' || temp === '['){
// 左括号则入栈
stack.push(temp);
}else{
// 右括号则匹配后出栈
let matchTemp = stack[stack.length-1];
if(temp === ')' && matchTemp !== '(') return false;
if(temp === ']' && matchTemp !== '[') return false;
if(temp === '}' && matchTemp !== '{') return false;
stack.pop();
}
i++;
}
if(stack.length !== 0) return false;
return true;
};