老师,第20道题目今天我是面试到了,然后我用了3个栈, 分别存放"(", “[”, “{”, 但是碰到 "([)]"这个用例就挂了,
然后我到您github上看了答案,是只用了一个栈就够了,我也看明白了。呃,在面试中,我自己直观的方式是想用3个栈,如果是3个栈,可以做吗,哈哈哈。
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack_0 = []; // (
let stack_1 = []; // [
let stack_2 = []; // {
for( let i = 0; i < s.length; i ++ ){
let nowChar = s.charAt(i);
if( nowChar == '(' ){
stack_0.push(nowChar);
}else if( nowChar == '[' ){
stack_1.push(nowChar);
}else if( nowChar == '{' ){
stack_2.push(nowChar);
}
if( nowChar == ')' ){
if( stack_0.length == 0 ){
return false;
}
stack_0.pop();
}else if( nowChar == ']' ){
if( stack_1.length == 0 ){
return false;
}
stack_1.pop();
}else if( nowChar == '}' ){
if( stack_2.length == 0 ){
return false;
}
stack_2.pop();
}
} // for i
if( stack_0.length > 0 || stack_1.length > 0 || stack_2.length > 0 ){
return false;
}
return true;
};