python中的栈

在 Python 中,栈是一种数据结构,常用于需要遵循 后进先出(LIFO) 原则的操作。在刷算法题时,栈常用来解决括号匹配、单调栈、深度优先搜索等问题。

以下是 Python 中栈的相关语法和常用操作。

栈的实现方式

Python 中可以使用以下两种方式实现栈:

  1. 使用列表 (list)。
  2. 使用 collections.deque(双端队列)。

使用列表实现栈

stack = []

# 压入元素
stack.append(1)
stack.append(2)
stack.append(3)

# 弹出元素
top = stack.pop()  # 返回 3,栈变为 [1, 2]

# 查看栈顶元素(不移除)
top = stack[-1]  # 返回 2

# 检查栈是否为空
is_empty = len(stack) == 0

使用 collections.deque

deque 的性能比列表更优,因为它对两端的操作时间复杂度为 O(1),而列表的插入/删除操作可能会导致 O(n) 的开销。

from collections import deque

stack = deque()

# 压入元素
stack.append(1)
stack.append(2)
stack.append(3)

# 弹出元素
top = stack.pop()  # 返回 3

# 查看栈顶元素
top = stack[-1]  # 返回 2

# 检查栈是否为空
is_empty = len(stack) == 0

栈的常见应用

1. 括号匹配问题

def isValid(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    
    for char in s:
        if char in mapping:  # 是右括号
            top_element = stack.pop() if stack else '#'  # 获取栈顶元素
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)  # 是左括号,压入栈中
    return not stack

# 示例
print(isValid("()[]{}"))  # True
print(isValid("(]"))      # False

2. 单调栈(求解下一个更大元素)

def nextGreaterElements(nums):
    stack = []
    res = [-1] * len(nums)
    
    for i in range(len(nums)):
        while stack and nums[i] > nums[stack[-1]]:
            index = stack.pop()
            res[index] = nums[i]
        stack.append(i)
    
    return res

# 示例
print(nextGreaterElements([2, 1, 2, 4, 3]))  # [4, 2, 4, -1, -1]

3. 深度优先搜索(DFS)

def dfs(graph, start):
    stack = [start]
    visited = set()
    
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.add(node)
            # 将邻接节点压入栈
            stack.extend(graph[node])
    
    return visited

# 示例图
graph = {
    1: [2, 3],
    2: [4],
    3: [],
    4: []
}
print(dfs(graph, 1))  # {1, 2, 3, 4}

4. 计算逆波兰表达式

def evalRPN(tokens):
    stack = []
    
    for token in tokens:
        if token not in "+-*/":
            stack.append(int(token))
        else:
            b = stack.pop()
            a = stack.pop()
            if token == '+':
                stack.append(a + b)
            elif token == '-':
                stack.append(a - b)
            elif token == '*':
                stack.append(a * b)
            elif token == '/':
                stack.append(int(a / b))  # 符合题目要求的整除
            
    return stack[0]

# 示例
tokens = ["2", "1", "+", "3", "*"]
print(evalRPN(tokens))  # 9

总结

  • 常用方法append(压入栈),pop(弹出栈顶),[-1](查看栈顶)。
  • 应用场景:括号匹配、单调栈、DFS、逆波兰表达式计算、直方图最大矩形面积等。
  • 性能选择:对于频繁插入和删除操作,建议使用 collections.deque,性能优于 list

在刷题时,熟练使用栈的基本操作和思想,将显著提升解题效率。

posted @ 2025-01-05 21:38  清澈的澈  阅读(77)  评论(0)    收藏  举报