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

题目链接:20. 有效的括号 - 力扣(LeetCode)

思路:

由于栈结构的特殊性,非常适合做对称匹配类的题目。

首先弄清楚,字符串里的括号出现不匹配的几种情况。一是字符串里左方向的括号多余了所以不匹配,二是括号没有多余但是括号的类型没有匹配上,三是字符串右方向的括号多余了。

那么使用栈对字符串进行遍历就是我们要完成的事。如果遍历完字符串后发现栈不为空,则是左方向的括号多余了;如果遍历过程中发现不匹配的字符,则是括号类型没有对上;如果遍历过程中栈已经空了,则是右方向的括号多余了。

# 仅使用栈
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 True if not stack else False

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

题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)

思路:

此题同样可以用栈的应用来解决,在python中用list来实现栈的功能和应用,对字符串进行遍历,遍历过程中将遍历的每个字符与栈顶的字符进行对比,若相同则不放入栈中,同时将栈顶的字符抛出,直到遍历完成为止,最后对栈遍历将其中的每个元素转化为一个字符串。

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for item in s:   
            if not stack:
                stack.append(item)
            elif item == stack[-1] :
                stack.pop()
            else:
                stack.append(item)
        t = ''
        for i in stack:
            t += str(i)
        s = t
        return s

# 代码随想录
# 方法一,使用栈
class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list()
        for item in s:
            if res and res[-1] == item:
                res.pop()
            else:
                res.append(item)
        return "".join(res)  # 字符串拼接

# 方法二,使用双指针模拟栈,如果不让用栈可以作为备选方法。
class Solution:
    def removeDuplicates(self, s: str) -> str:
        res = list(s)
        slow = fast = 0
        length = len(res)

        while fast < length:
            # 如果一样直接换,不一样会把后面的填在slow的位置
            res[slow] = res[fast]
            
            # 如果发现和前一个一样,就退一格指针
            if slow > 0 and res[slow] == res[slow - 1]:
                slow -= 1
            else:
                slow += 1
            fast += 1
            
        return ''.join(res[0: slow])

题目链接:150. 逆波兰表达式求值 - 力扣(LeetCode)

思路:

逆波兰表达式是将每两个数之间的运算符挪到后一个数的后面,但括号不变,也就是一个相邻字符串消除的过程,在找到一个运算符之后,就用该运算符将前两位数字消除再存入运算后的数字。

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for item in tokens:
            if item == '+':
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(int(p2 + p1))
            elif item == '-':
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(int(p2 - p1))
            elif item == '*':
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(int(p2 * p1))
            elif item == '/':
                p1 = stack.pop()
                p2 = stack.pop()
                stack.append(int(p2 / p1))
            else:
                stack.append(int (item))
        return int(stack.pop())

# 版本一  使用操作符
from operator import add, sub, mul

class Solution:
    op_map = {'+': add, '-': sub, '*': mul, '/': lambda x, y: int(x / y)}
    
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            if token not in {'+', '-', '*', '/'}:
                stack.append(int(token))
            else:
                op2 = stack.pop()
                op1 = stack.pop()
                stack.append(self.op_map[token](op1, op2))  # 第一个出来的在运算符后面
        return stack.pop()

# 版本二  使用eval相对较慢
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()) # 如果一开始只有一个数,那么会是字符串形式的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值