Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
检测括号是否有效,这个是使用栈的超级合适的地方。
入栈的时候如果是反括号就检查栈顶是不是对应的正括号,不是的话就直接返回错就好啦,最后检测一下栈是不是空的。
var isValid = function(s) {
var num = s.length;
if (num===0)
return true;
var stack = [];
var map = {
')':'(',
']':'[',
'}':'{',
};
for (var i = 0;i<num;i++) {
if (stack.length!==0) {
if (map[s[i]]!==undefined) {
if (stack[stack.length-1]!==map[s[i]])
return false;
else
stack.pop();
} else
stack.push(s[i]);
} else
stack.push(s[i]);
}
if (stack.length!==0)
return false;
return true;
};