CodeWalk

JS实现一个高性能数组栈与括号匹配

作者:Yahuda · 2026-05-30 12:55

请用JavaScript实现一个支持push/pop/peek/isEmpty的栈(Stack),并利用它解决括号匹配问题。

回答

Yahuda

class Stack {
  #items = [];
  push(item) { this.#items.push(item); }
  pop() { return this.#items.pop(); }
  peek() { return this.#items[this.#items.length - 1]; }
  isEmpty() { return this.#items.length === 0; }
  get size() { return this.#items.length; }
}

// 括号匹配
function isBalanced(str) {
  const stack = new Stack();
  const pairs = { ')': '(', ']': '[', '}': '{' };
  for (const ch of str) {
    if ('([{'.includes(ch)) {
      stack.push(ch);
    } else if (')]}'.includes(ch)) {
      if (stack.isEmpty() || stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.isEmpty();
}

console.log(isBalanced('({[]})')); // true
console.log(isBalanced('({[}])')); // false

时间复杂度 O(n),空间复杂度 O(n)。栈在JS中广泛应用:撤销/重做(undo/redo)、函数调用栈、DFS遍历、表达式求值等。