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

20. 有效的括号

题解

https://programmercarl.com/0020.%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7.html
“由于栈结构的特殊性,非常适合做对称匹配类的题目”
不匹配的三种情况:

  1. 左右括号个数不匹配 - 左方括号多余
  2. 左右括号个数不匹配 - 右方括号多余
  3. 个数匹配,单纯配不上
    思路:
    从头遍历,每遇到一个左括号,将他对应的右括号加入栈,每遇到一个右括号,如果栈中最后一个是这个右括号,从栈中移除这个右括号,继续遍历
    return false:
  4. 每遇到一个右括号,如果栈中最后不是需要的右括号
  5. 每遇到一个右括号,如果栈已经空了
  6. 遍历完所有的括号,栈非空
    return true: 遍历完成后,栈也是空的
    code:
 class Solution:
    def isValid(self, s: str) -> bool:
        s = list(s)
        stack = []
        for i in range(len(s)):
            if s[i] == '(':
                stack.append(')')
            elif s[i] == '[':
                stack.append(']')
            elif s[i] == '{':
                stack.append('}')
            elif s[i] == ')' and len(stack) != 0 and stack[-1] == ')':
                stack.pop()
            elif s[i] == ']' and len(stack) != 0 and stack[-1] == ']':
                stack.pop()
            elif s[i] == '}' and len(stack) != 0 and stack[-1] == '}':
                stack.pop()
            else:
                return False
        if len(stack) != 0:
            return False
        else:
            return True

更精简的答案:

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

code 是很好写的,主要是这种思路

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

初步想法

跟上一题一样的思路

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

题解

https://programmercarl.com/1047.%E5%88%A0%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E6%89%80%E6%9C%89%E7%9B%B8%E9%82%BB%E9%87%8D%E5%A4%8D%E9%A1%B9.html

150. 逆波兰表达式求值

初步想法

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        operations = ['+','-','*','/']
        for item in tokens:
            if item not in operations:
                stack.append(int(item))
                print(stack)
            elif item == '+':
                new_token = stack[-2] + stack[-1]
                stack = stack[0:-2]
                stack.append(new_token)
                print(stack)
            elif item == '-':
                new_token = stack[-2] - stack[-1]
                stack = stack[0:-2]
                stack.append(new_token)
                print(stack)
            elif item == '*':
                new_token = stack[-2] * stack[-1]
                stack = stack[0:-2]
                stack.append(new_token)
                print(stack)
            elif item == '/':
                if stack[-2] / stack[-1] > 0:
                    new_token = floor(stack[-2] / stack[-1])
                else:
                     new_token = ceil(stack[-2] / stack[-1])
                stack = stack[0:-2]
                stack.append(new_token)
                print(stack)
        return stack[0]

但是超时了…

题解

https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html
跟我想的一样
那就是code的问题了

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for item in tokens:
            if item not in {"+", "-", "*", "/"}:
                stack.append(item)
            else:
                first_num, second_num = stack.pop(), stack.pop()
                stack.append(
                    int(eval(f'{second_num} {item} {first_num}'))   # 第一个出来的在运算符后面
                )
        return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值