#20. Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
这种括号对称的问题,就用stack push pop做。
var isValid = function(s) {
if(s.length%2 != 0) {
return false;
}
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]===')') {
if(stack.pop()==='(') {
}
else {
return false;
}
}
else if(s[i]===']') {
if(stack.pop()==='[') {
}
else {
return false;
}
}
else {
if(stack.pop()==='{') {
}
else {
return false;
}
}
}
if(stack.length === 0) {
return true;
}
else {
return false;
}
};