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

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]

 

你可能感兴趣的:(哈希算法,算法)