碰到[
{
(
入栈
碰到]
}
)
弹出栈顶做比较,不匹配直接返回false
注意循环遍历完后需要再次判断stack.length是否为0
function isValid( s ) {
let stack = [];
for(let i=0; i<s.length; i++){
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
stack.push(s[i]);
else
if( s[i]==')' && stack.pop()=='(' ||
s[i]=='}' && stack.pop()=='{' ||
s[i]==']' && stack.pop()=='[' )
continue;
else
return false;
}
if(stack.length!=0)
return false;
return true;
}
module.exports = {
isValid : isValid
};