数据结构与算法@括号匹配

概述

写一个函数判断给定算术表达式中的括号是否匹配,例如1/2+(3+4是不匹配。

详述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 判断一个算术表达式中的括号是否匹配;
function parenthesesChecker(symbols) {
const stack = new Stack();
const opens = "([{";
const closers = ")]}";
let balanced = true;
let index = 0;
let symbol;
let top;

while (index < symbols.length && balanced) {
symbol = symbols[index];
if (opens.indexOf(symbol) >= 0) {
stack.push(symbol);
} else if (stack.isEmpty()) {
balanced = false;
} else {
top = stack.pop();
if (!(opens.indexOf(top) === closers.indexOf(symbol))) {
balanced = false;
}
}
index++;
}
return balanced && stack.isEmpty();
}

console.log("{([])}", parenthesesChecker("{([])}")); // true
console.log("{{([][])}()}", parenthesesChecker("{{([][])}()}")); // true
console.log("[{()]", parenthesesChecker("[{()]")); // false

参考