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

20. Valid Parentheses

use stack to add every left parenthesis and add the right counterpart into a stack. if the next element is not left and equals to the last element in the stack (in this case, the element is a right parenthesis) the last element is poped. Iterate through, all added elements will be poped if the string is valid. Not only the numbers need to match but also the order.

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

1047. Remove All Adjacent Duplicates In String

append every element into a stack. if the next element == the last element in the stack, pop the last element in the stack.

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for i in s:
            if len(stack) > 0:
                if stack[-1] == i:
                    stack.pop()
                    continue

            stack.append(i)
        return ''.join(stack)

150. Evaluate Reverse Polish Notation

To solve this question, append a number into the stack. when having an operator. pop the last two elements in the stack and do the operation on it. 
 

class Solution:
    op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []

        for i in tokens:
            if i not in ['+', '-', '*', '/']:
                stack.append(int(i))
            else:
                second = stack.pop()
                first = stack.pop()
                new_num = self.op_map[i](first,second)
                stack.append(new_num)
        return stack.pop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值