算法练习Day10 (Leetcode/Python-堆栈和队列)

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.

Example 1:

Input: s = "()"
Output: true

思路:

利用堆栈后进先出的顺序来验证是否符合正确的order。这道题乍看不难,但是我第一次return False有遗漏情况,即右括号有多余的情况。建议先列出来所有要return False的情况,这样写起来更有条理。其实就三种不匹配的情况:1. 左括号多余:已经遍历完,但是栈不为空。2. 顺序不匹配:栈不为空,但是新输入的元素不匹配栈里top的元素。3. 右括号多余:栈已经空了,但是还有右括号。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        record = []
        for char in s:
            if char == "(" or char =="[" or char =="{":
                if char == "(":
                    record.append(")")
                if char == "[":
                    record.append("]")
                if char == "{":
                    record.append("}")
            elif not record or record[-1] != char:
                return False
            else:
                record.pop()
        if record:
            return False
        return True

复杂度: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(object):
    def removeDuplicates(self, s):
        """
        :type s: str
        :rtype: str
        """
        output = []
        for char in s:
            if output and output[-1] == char:
                output.pop() 
            else:
                output.append(char) 
        return ''.join(output)

        

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

思路:建立一个stack用来存逆波兰表达式,从左到右扫描给定的波兰表达式:

  • 如果遇到数,数入栈。
  • 如果遇到操作符,栈顶两个元素出栈,先出栈的数在运算符右侧,后出栈的在运算符左侧,运算完后,将运算值入栈。

遍历完全给定的波兰表达式后,栈内只有一个值,也就是最后的结果

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []

        for c in tokens:
            # if not operation, push to stack 
            if c not in ['+', '-', '*', '/']:
                stack.append(int(c))
            # if it is an operation
            else:
                right = stack.pop()
                left = stack.pop()

                # calculate and push results
                if c == '+':
                    stack.append(left + right)
                elif c == '-':
                    stack.append(left - right)
                elif c == '*':
                    stack.append(left * right) 
                else:
                    stack.append(int(left / right)) # “/” is exact division. Remember to add int 
        # Only one value is left in the stack. Return. 
        return stack.pop()

  • 14
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值