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

20. Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order.

  3. Every close bracket has a corresponding open bracket of the same type.

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        tab = {
            ')':'(',
            ']':'[',
            '}':'{'
        }

        for x in s:
            if x in tab:
                if not stack:
                    return False
                if tab[x] != stack.pop():
                    return False
            else:
                stack.append(x)
        
        return not stack


  • list for stack
  • O(n), O(n)

=================================================

1047. Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them. We repeatedly make duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = “abbaca”
Output: “ca”
Explanation:
For example, in “abbaca” we could remove “bb” since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is “aaca”, of which only “aa” is possible, so the final string is “ca”.

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

  • O(n), O(n)

150. Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

  • The valid operators are '+', '-', '*', and '/'.
  • Each operand may be an integer or another expression.
  • The division between two integers always truncates toward zero.
  • There will not be any division by zero.
  • The input represents a valid arithmetic expression in a reverse polish notation.
  • The answer and all the intermediate calculations can be represented in a 32-bit integer.

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
  • Sol1:
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = list()
        for x in tokens:
            if x not in "+-*/":
                stack.append(x)
            else:
                r = int(stack.pop())
                l = int(stack.pop())
                if x=='+':
                    stack.append(l+r)
                if x=='-':
                    stack.append(l-r)
                if x=='*':
                    stack.append(l*r)
                if x=='/':
                    stack.append(int(l/r))
        return int(stack.pop())
  • Sol 2:
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        op_set = {'+', '-', '*', '/'}
        def operate(a:str,b:str,op:str) -> str:
            a,b  = int(a), int(b)
            if op == '+':
                return str(a+b)
            elif op == '-':
                return str(a-b)
            elif op == '*':
                return str(a*b)
            elif op == '/':
                return str(int(a/b))
                #return str(a//b) this is not correct for negative
        
        stack = list()
        for x in tokens:
            #print(stack)
            if x not in op_set:
                stack.append(x)
            else:
                if stack:
                    b=stack.pop()
                    a=stack.pop()
                    stack.append(operate(a,b,x))
        return int(stack.pop())
  • O(n), O(n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值