代码随想录学习Day 10

20.有效的括号

题目链接

讲解链接

不匹配的情况总共有三种:左括号多了、右括号多了以及左右括号不匹配。

在匹配左括号的时候,右括号先入栈,就只需要比较当前元素和栈顶相不相等就可以了,比左括号先入栈代码实现要简单。

最后字符串遍历完之后,如果栈是空的,就说明左右括号全都匹配。

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

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

题目链接

讲解链接

本题非常简单,只需要遍历字符串中的元素,将与栈顶元素不同的元素入栈,若相同则不入栈并弹出栈顶元素即可。

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for i in s:
            if stack and i == stack[-1]:  # 当栈不为空且当前元素与栈顶元素相同
                stack.pop()  # 弹出栈顶元素
            else:
                stack.append(i)  # 反之将其入栈
        return ''.join(stack)  # 转为字符串

双指针法如下 

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. 逆波兰表达式求值 

题目链接

讲解链接

第一种采用eval的方法,但速度较慢

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for i in tokens:
            if i in {'+', '-', '*', '/'}:  # 若i为运算符
                a = int(stack.pop())  # 弹出第一个元素
                b = int(stack.pop())  # 弹出第二个元素
                c = eval('%d%s%d'%(b,i,a))  # 转为int型并用eval进行运算,注意先出栈的在运算符后
                stack.append(c)
            else:
                stack.append(i)  # 若是数字则直接入栈           
        return int(stack.pop())  # 如果字符串中仅有一个数字,则是字符串形式,需要转为int

第二种方法采用字典

from operator import add, sub, mul
class Solution:
    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.map[token](op1, op2))  # 第一个出来的在运算符后面
        return stack.pop()

你可能感兴趣的:(学习,python,leetcode)