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.
檢測(cè)括號(hào)是否有效识埋,這個(gè)是使用棧的超級(jí)合適的地方痢站。
入棧的時(shí)候如果是反括號(hào)就檢查棧頂是不是對(duì)應(yīng)的正括號(hào)鸽粉,不是的話就直接返回錯(cuò)就好啦,最后檢測(cè)一下棧是不是空的。
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;
};