Description:
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.
My code:
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
if(s.length % 2 == 1) {
return false;
}
let arr = s.split("");
// use stack to solve, if the character == '(' || '[' || '{', push into stack, if the character == ')' || ']' || '}', check if the character match the top of stack, if true, pop the top, else return false, finally check if the stack is empty, if empty return true, else return false
let stack = [];
for(let i = 0; i < arr.length; i++) {
if(arr[i] == '(' || arr[i] == '[' || arr[i] == '{') {
stack.push(arr[i]);
} else if((arr[i] == ')' && stack[stack.length-1] == '(') || (arr[i] == ']' && stack[stack.length-1] == '[') || (arr[i] == '}' && stack[stack.length-1] == '{')) {
stack.pop();
} else {
return false;
}
}
if(stack.length == 0) {
return true;
} else {
return false;
}
};
Note: 使用一个数组以栈的形式存储括号的左半边,每遇到一个右括号,就验证括号是否对应的,如果不是就直接return false。最后判断栈是否为空,如果空则全部匹配正确,return true。