何謂平衡括號問題?
平衡括號也叫有效括號,問題描述有很多種,看下面中的一種描述:
給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
1、左括號必須用相同類型的右括號閉合。
2、左括號必須以正確的順序閉合。
解決此問題需要借助棧的知識,如下:

棧
引入創(chuàng)建好的 Stack 類。
代碼實現(xiàn)如下:
// symbols 為傳入的字符串
function parenthesesChecker(symbols) {
// 創(chuàng)建 Stack 類
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();
}
// test
console.log('([])', parenthesesChecker('([])')); // ([]) true
console.log('{([])}', parenthesesChecker('{([])}')); // {([])} true
console.log('(([()])))', parenthesesChecker('(([()])))')); // (([()]))) false
console.log('([()[]()])()', parenthesesChecker('([()[]()])()')); // ([()[]()])() true
平衡(有效)括號問題有很多的變形描述,這只是一種,這里的解決思路也是JavaScript 的方式,其他的描述方式解決方法也不一樣,這里只是提供一個解決思路作為參考。