代码随想录算法训练营第11天

发布时间:2024年01月23日

20. 有效的括号

class Solution:
    def isValid(self, s: str) -> bool:
        hash = {'{':'}','[':']','(':')','?':'?'}
        stack = ['?']
        for c in s:
            if c in hash:
                stack.append(c)
            elif hash[stack.pop()]!=c:
                return False

        return len(stack) ==1

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

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

150. 逆波兰表达式求值

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        dic = {'+':1,'-':1,'*':1,'/':1}
        for c in tokens:
            if c not in dic:
                stack.append(int(c))
            else:
                if c=='+':
                    tmp =  stack.pop() + stack.pop()
                    stack.append(tmp)
                elif c=='-':
                    tmp =  -stack.pop() + stack.pop()
                    stack.append(tmp)
                elif c=='*':
                    tmp =  stack.pop() * stack.pop()
                    stack.append(tmp)
                elif c=='/':
                    tmp =  1/stack.pop() * stack.pop()
                    stack.append(int(tmp))
        return stack[-1]

?

文章来源:https://blog.csdn.net/weixin_44733295/article/details/135742762
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。