代码随想录算法训练营第11天| 20. 有效的括号 1047. 删除字符串中的所有相邻重复项 150. 逆波兰表达式求值

20. Valid Parentheses

  • 经典的栈问题
  • 遇到左侧符号则向栈中添加
  • 遇到右侧符合则检测栈顶元素,如果是配对符号,则弹出栈顶元素,否则return False
  • 如果最后栈为空(长度为0),则return True,否则False
class Solution(object):
    def isValid(self, s):
        if len(s) == 0:
            return True
        stack = []
        for c in s:
            if c == '(' or c == '{' or c == '[':
                stack.append(c)
            else:
                if len(stack) == 0:
                    return False
                else:
                    temp = stack.pop()
                    if c == ')':
                        if temp != '(':
                            return False
                    elif c == ']':
                        if temp != '[':
                            return False
                    elif c == '}':
                        if temp != '{':
                            return False
        return True if len(stack) == 0 else False

1047. Remove All Adjacent Duplicates In String

class Solution(object):
    def removeDuplicates(self, s):
        s_stack = []
        for i in s:
            if len(s_stack) == 0 or s_stack[-1] != i:
                s_stack.append(i)
            elif s_stack[-1] == i:
                s_stack.pop()
        return "".join(s_stack)

150. Evaluate Reverse Polish Notation

# 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
class Solution(object):
    def evalRPN(self, tokens):
        stack = []
        for t in tokens:
            if t not in "+-*/":
                stack.append(int(t))
            else:
                r, l = stack.pop(), stack.pop()
                if t == "+":
                    stack.append(l+r)
                elif t == "-":
                    stack.append(l-r)
                elif t == "*":
                    stack.append(l*r)
                else:
                    stack.append(int(float(l)/r))
        return stack.pop()

你可能感兴趣的:(代码随想录算法训练营第二期,算法,职场和发展)