训练营Day11 | 栈与队列

57 阅读1分钟

利用栈先进后出的特点

可以进行就近匹配

20. 有效的括号

class Solution: 
    def isValid(self, s: str) -> bool: 
        matched = {'(':')', '{':'}', '[':']'}
        left = []
        for i in s:
            if i == '(' or i == '[' or i == '{':
                left.append(i) 
            else: 
                if not left or matched[left.pop()] != i: 
                    return False 
        if left: 
            return False 
        return True

1047. 删除字符串中的所有相邻重复项

class Solution: 
    def removeDuplicates(self, s: str) -> str: 
        res = [] 
        for i in s: 
            if res and res[-1] == i: 
                res.pop() 
            else: 
                res.append(i) 
        return ''.join(res)

150. 逆波兰表达式求值

可以参考Leetcode下方的思路

  • 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
def evalRPN(self, tokens: List[str]) -> int:
    nums = []
    for t in tokens:
        if t not in ['+', '-', '*', '/']:
            nums.append(int(t))
        elif t == '+':
            tmp = nums.pop() + nums.pop()
            nums.append(tmp)
        elif t == '-':
            tmp = - nums.pop() + nums.pop()
            nums.append(tmp)
        elif t == '*':
            tmp = nums.pop() * nums.pop()
            nums.append(tmp)
        elif t == '/':
            tmp = int(1 / nums.pop() * nums.pop())
            nums.append(tmp)
    return nums[-1]