Day 11 | 20. 有效的括号 、1047. 删除字符串中的所有相邻重复项 、150. 逆波兰表达式求值

20. 有效的括号

讲完了栈实现队列,队列实现栈,接下来就是栈的经典应用了。

大家先自己思考一下 有哪些不匹配的场景,在看视频 我讲的都有哪些场景,落实到代码其实就容易很多了。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0020.有效的括号.html

思考

class Solution:
    def isValid(self, s: str) -> bool:
        stack = [] 
        for c in s:
            if c in '([{':
                stack.append(c)
            else:
                if c == ')' and len(stack)>0 and stack[-1] == '(':
                    stack.pop()
                elif c == ']' and len(stack)>0 and stack[-1] == '[':
                    stack.pop()
                elif c == '}' and len(stack)>0 and stack[-1] == '{':
                    stack.pop()
                else:
                    return False
        if len(stack) == 0:
            return True
        else:
            return False

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

栈的经典应用。

要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么。

题目链接/文章讲解/视频讲解:https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html

思考

天天爱消除模式,使用栈来处理匹配问题。

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

150. 逆波兰表达式求值

本题不难,但第一次做的话,会很难想到,所以先看视频,了解思路再去做题

题目链接/文章讲解/视频讲解:https://programmercarl.com/0150.逆波兰表达式求值.html

思考

逆波兰表达式主要有以下两个优点:

去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。

适合用栈操作运算:遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中。

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for c in tokens:
            if c == '+':
                res = stack.pop() + stack.pop()
                stack.append(res)
            elif c == '-':
                y = stack.pop()
                x = stack.pop()
                res = x - y
                stack.append(res)
            elif c == '*':
                res = stack.pop() * stack.pop()
                stack.append(res)
            elif c == '/':
                y = stack.pop()
                x = stack.pop()
                res = int(x / y)
                stack.append(res)
            else:
                stack.append(int(c))
        return stack[-1]
posted @ 2024-06-01 15:09  forrestr  阅读(29)  评论(0)    收藏  举报