何时使用
- 括号、标签、路径、表达式等嵌套结构:最近打开的最先关闭
- "逆波兰 / 后缀表达式""计算器""解码
3[a2[c]]"→ 操作数栈(+ 运算符栈) - "下一个更大 / 更小元素""还要等几天""左右第一个比它矮的"→ 单调栈
- "以每个元素为最小值 / 最大值能延伸多远""最大矩形面积"→ 单调栈求左右边界
- "O(1) 取当前最小值 / 最大值"且元素按后进先出变化 → 辅助栈
- 递归改迭代(DFS、中序遍历)→ 显式栈
模板 1:配对与求值栈
遇到"开"就压栈,遇到"闭"就检查并弹出;后缀表达式遇到运算符就弹两个操作数。
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
st = []
for c in s:
if c in pairs:
if not st or st[-1] != pairs[c]:
return False
st.pop()
else:
st.append(c)
return not st # 最后必须为空
def eval_rpn(tokens):
st = []
for t in tokens:
if t in {"+", "-", "*", "/"}:
b, a = st.pop(), st.pop() # 先弹出的是右操作数
st.append(apply(t, a, b)) # 除法向零截断:int(a / b)
else:
st.append(int(t))
return st[0]
function isValid(s) {
const pairs = { ")": "(", "]": "[", "}": "{" };
const st = [];
for (const c of s) {
if (c in pairs) {
if (!st.length || st[st.length - 1] !== pairs[c]) return false;
st.pop();
} else st.push(c);
}
return st.length === 0; // 最后必须为空
}
function evalRPN(tokens) {
const st = [];
for (const t of tokens) {
if ("+-*/".includes(t) && t.length === 1) {
const b = st.pop(), a = st.pop(); // 先弹出的是右操作数
st.push(apply(t, a, b)); // 除法向零截断:Math.trunc(a / b)
} else st.push(Number(t));
}
return st[0];
}
- 弹栈前先判空;循环结束后检查栈是否为空
- 减法和除法注意操作数顺序:
a op b,其中b先出栈 - 整数除法看清取整方向:Python
//、JSMath.floor向下取整,向零截断用int(a / b)/Math.trunc