检查数学表达式不起作用的函数.
我在chrome上调试了这个,我看到当它到达第一个pop(stack.pop()!== chars[i])时,它返回false,但它不应该.
var smarter_validate = function(str) {
var chars = str.split('');
var stack = [];
var lookup = {
'(': ')',
'[': ']',
'{': '}',
'<': '>'
};
var left = Object.keys(lookup);
var right = Object.keys(lookup).map(function(key) {
return lookup[key]
});
for (var i = 0; i < chars.length; i++) {
if (left.indexOf(chars[i]) !== (-1)) {
stack.push(chars[i]);
} else if (right.indexOf(chars[i]) !== (-1)) {
if ((stack.length === 0) || (stack.pop() !== chars[i])) {
return false;
}
}
}
return (stack.length === 0);
};
console.log("SMART VALIDATE" + smarter_validate('(3+4[*2{6+8}])'));
Run Code Online (Sandbox Code Playgroud)
您实际上必须比较弹出值的相应结束字符chars[i],而不是弹出值本身.
所以你需要这样做
if (stack.length === 0 || lookup[stack.pop()] !== chars[i]) {
Run Code Online (Sandbox Code Playgroud)
现在,当您{从堆栈中,您将从中查找相应的结束字符lookup,并将其与当前结束字符进行比较.
或者,您可以简单地在堆栈中按下预期的结束字符,这样您就不会在比较期间执行查找,就像这样
stack.push(lookup[chars[i]]);
Run Code Online (Sandbox Code Playgroud)