1. 程式人生 > >python資料結構之棧和佇列

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))