栈:括号匹配与表达式求值
一、面试常考点
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
}