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

一、今日任务

二、有效的括号

2.1 题目:20. 有效的括号

2.2 解题过程

这是一题非常典型的栈题。

先约定用列表list模拟栈,list.append(x) 代替 push,list.pop() 代替 pop,其他的栈函数在解题过程中慢慢增加。

再应用到了一个top()函数。具体代码如下:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        if len(s) == 0:
            return True
        if len(s)%2 == 1:
            return False
        index = 0
        while index < len(s):
            if s[index] == '(' or s[index] == '[' or s[index] == '{':
                stack.append(s[index])
            elif len(stack) > 0 :
                if s[index] == ')' and stack[len(stack)-1] == '(':
                    stack.pop()
                elif s[index] == ']' and stack[len(stack)-1] == '[':
                    stack.pop()
                elif s[index] == '}' and stack[len(stack)-1] == '{':
                    stack.pop()
                else:
                    return False
            else:
                return False
            index += 1
        if len(stack) == 0:
            return True
        else:
            return False

2.3 阅读材料改进

随想录中的思路或者说是解法更加完美,我的代码还是一如既往的缝缝补补。

以下是复现代码:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        index = 0
        while index < len(s):
            if s[index] == '(':
                stack.append(')')
            elif s[index]=='[':
                stack.append(']')
            elif s[index]=='{':
                stack.append('}')
            elif not stack or s[index] != stack[len(stack)-1]:
                return False
            else:
                stack.pop()
            index += 1
        return not stack

三、删除字符串中的所有相邻重复项

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

3.2 解题过程

class Solution(object):
    def removeDuplicates(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 思路:一直与栈顶对比。直至遍历完整个字符串。
        if len(s) == 0:
            return s
        stack = []
        stack.append(s[0])
        index = 1
        while index < len(s):
            if stack and s[index] == stack[len(stack)-1]:
                stack.pop()
                index += 1
            elif not stack or s[index] != stack[len(stack)-1]:
                stack.append(s[index])
                index += 1
        return ''.join(stack)

3.3 阅读材料改进

随想录提出另外一个快慢指针的思路。以下是复现代码。

class Solution(object):
    def removeDuplicates(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = list(s)
        slow = fast = 0
        length = len(res)
        while fast < length:
            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])

四、逆波兰表达式求值

4.1 题目:150. 逆波兰表达式求值

4.2 解题过程

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack_num = []
        index = 0
        while index < len(tokens):
            temp = tokens[index]
            if temp == '+':
                temp1 = stack_num.pop()
                temp2 = stack_num.pop()
                stack_num.append(temp1 + temp2)
            elif temp == '-':
                temp1 = stack_num.pop()
                temp2 = stack_num.pop()
                stack_num.append(temp2 - temp1)
            elif temp == '/':
                temp1 = stack_num.pop()
                temp2 = stack_num.pop()
                stack_num.append(int(temp2/temp1))
            elif temp == '*':
                temp1 = stack_num.pop()
                temp2 = stack_num.pop()
                stack_num.append(temp1 * temp2)
            else:
                s = tokens[index]
                num = 0
                x = 1
                index_num = len(tokens[index]) - 1
                while s[index_num] != '-' and index_num >= 0:
                    num += (int(s[index_num])*(x))
                    x *= 10
                    index_num -= 1
                if s[0] == '-':
                    num = num*-1
                stack_num.append(num)
            index += 1
        return  stack_num.pop()

4.3 阅读材料改进

随想录借用了许多Python的内置函数。

以下是笔记:

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
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组找到长度最小的子数组,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值