python数据结构之栈和队列

1.功能实现

之前文章有,可以点开看看

队列

2.应用(1)括号匹配及后缀表达式

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        d = ["()", "[]", "{}"]
        for i in xrange(0, len(s)):
            stack.append(s[i])
            if len(stack) >= 2 and stack[-2]+stack[-1] in d:
                stack.pop()
                stack.pop()
        return len(stack) == 0

150. Evaluate Reverse Polish Notation(计算逆波兰表达式RPN)

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9

  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
后缀

class Solution:
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
 
        for s in tokens:
            if s in ['+','-','*','/']:
                b = stack.pop()
                a = stack.pop()
                if s == '+':
                    stack.append(a+b)
                elif s == '-':
                    stack.append(a-b)
                elif s == '*':
                    stack.append(a*b)
                else:
                    stack.append(int(a/b))
            else:
                stack.append(int(s))
                    
        ans = int(stack.pop())
        return ans        

中缀 

class Solution:
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
 
        for s in tokens:
            if s in ['+','-','*','/']:
                a = stack.pop(0)
                b = stack.pop(0)
                if s == '+':
                    stack.append(a+b)
                elif s == '-':
                    stack.append(a-b)
                elif s == '*':
                    stack.append(a*b)
                else:
                    stack.append(int(a/b))
            else:
                stack.append(int(s))
                    
        ans = int(stack.pop())
        return ans        

3.表达式计算与函数调用栈

Leetcode 224. Basic Calculator (基础计算器)

Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
 

class Solution:
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = []
        l = len(s)
        i = 0
        sgn,res = 1, 0              # 初始化res和符号变量sgn 存储前一个符号
 
        while i <= l-1:             # 遍历s
            ch = s[i]
            if ch ==' ':
                i += 1
                
            elif ch.isdigit():      # 处理遇到的数字(只可处理整数,其他的自行修改)
                j = i
                while j <= l-1:
                    j += 1
                    if j==l or not s[j].isdigit():
                        break              
                num = int(s[i:j])   # 此时的操作数为num
                i = j
            elif ch =='+' or ch == '-':     # 遇到符号,对前面的结果进行计算
                res += sgn * num
                sgn = 1 if ch=='+' else -1  # 更新符号变量 sgn
                i += 1
                num = 0
 
            elif ch == '(':             # 左括号,将当前结果和符号 压入栈中
                stack.append(res)
                stack.append(sgn)
                sgn,res = 1, 0          # 重置res和sgn     
                i += 1
            elif ch == ')':
                res += sgn*num          # 遇到右括号,对前面的结果进行计算
                res *= stack.pop()      # 并取出栈中存储的res和sgn
                res += stack.pop()
                i += 1
                num = 0                 # 注意重置num=0 ,否则右括号后面第一个运算符会重复计算num
 
        if num!= 0:                     # 如果此时num不为0 继续计算
            res += sgn*num
        return res

385. Mini Parser (迷你解析器)

Given a nested list of integers represented as a string, implement a parser to deserialize it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Note: You may assume that the string is well-formed:
String is non-empty.
String does not contain white spaces.
String contains only digits 0-9, [, - ,, ].
Example 1:
Given s = "324",You should return a NestedInteger object which contains a single integer 324.
Example 2:
Given s = "[123,[456,[789]]]",Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789.

def deserialize(self, s):
    return NestedInteger(s) if isinstance(s, int) else reduce(lambda a, x: a.add(self.deserialize(x)) or a, s, NestedInteger()) if isinstance(s, list) else self.deserialize(eval(s))

 

猜你喜欢

转载自blog.csdn.net/weixin_42307828/article/details/84927509