基本思路:
- 使用用两个栈,一个存储所有字符,一个只存储括号
- s1入栈所有字符
- 而遇到前括号,入栈s2;遇到后括号,查看s2最顶部的括号是否匹配
- 若匹配则让s2出栈该后括号匹配的前括号,即最顶部的括号
- 若不匹配,则返回括号不匹配或缺失的位置
stack.js:
class Stack {
constructor(){
this.dataStore=[];
this.top=0;
}
push(elem){
this.dataStore[this.top++]=elem;
}
peek(){
return this.dataStore[this.top-1]
}
pop(){
return this.dataStore[--this.top]
}
clear(){
this.top=0
}
length(){
return this.top;
}
}
module.exports=Stack
括号匹配:
const Stack = require('./stack.js')
function isMatch(str) {
const s1 = new Stack();
const s2 = new Stack();
let nums = '';
const sign1='+-*/()[]{}';
const sign2='(){}[]';
for (let i = 0; i < str.length; i++) {
if (sign2.indexOf(str[i]) > -1){
switch (str[i]) {
case '(':
case '[':
case '{': s2.push(str[i]);break;
case ')':
if (s2.peek() != '(') {
return `在${s1.peek()}后括号不匹配`
};
s2.pop()
break;
case ']':
if (s2.peek() != '[') {
return `在${s1.peek()}后括号不匹配`
};
s2.pop()
break;
case '}':
if (s2.peek() != '{') {
return `在${s1.peek()}后括号不匹配`
};
s2.pop()
break;
}
}
if(sign1.indexOf(str[i])>-1){
s1.push(str[i]);
continue;
}
while ('0' <= str[i] && str[i] <= '9' || str[i] == '.') {
nums += str[i]
i++;
}
i--;
s1.push(nums)
nums='';
}
return s2.length() > 0 ? `在末尾处,${s1.peek()}后括号不匹配` : '括号匹配';
}