跳到正文
前端知识库
算法

栈:括号匹配与表达式求值

遇左括号入栈,遇右括号弹栈并校验配对。(深入阅读:括号匹配实现)

1 分钟

栈:括号匹配与表达式求值

一、面试常考点

1. 括号匹配核心

遇左括号入栈,遇右括号弹栈并校验配对。(深入阅读:括号匹配实现

2. 结束条件

遍历完后栈必须为空。(深入阅读:括号匹配实现

二、示例代码

function isValid(s) {
  const map = { ')': '(', ']': '[', '}': '{' }
  const st = []
  for (const ch of s) {
    if (!map[ch]) st.push(ch)
    else if (st.pop() !== map[ch]) return false
  }
  return st.length === 0
}