leetcode-227-基本计算器②

题目描述:

 

 

方法一:中缀转后缀

#!_*_coding:utf-8_*_
class Solution:
    def calculate(self, s: str) -> int:
        def in_to_suffix(s):
            priority = {'+': 1, '-': 1, '*': 2, '/': 2}
            s.replace(" ", "")
            result = []
            stack = []
            for j,i in  enumerate(s):
                if i in priority.keys():
                    while stack and stack[-1] in priority.keys() and priority[i] <= priority[stack[-1]]:
                        result.append(stack.pop())
                    stack.append(i)
                else:
                    if j!=0 and s[j-1].isdigit():
                        i = int(result.pop())*10+int(i)
                    result.append(i)
            while stack:
                result.append(stack.pop())
            print(result)
            return result

        def evalRPN(tokens):
            f1 = lambda a, b: a + b
            f2 = lambda a, b: a - b
            f3 = lambda a, b: a * b
            f4 = lambda a, b: a // b
            maps = {'+': f1, '-': f2, '*': f3, '/': f4}
            stack = []
            for token in tokens:
                if token in maps:
                    a = stack.pop()
                    b = stack.pop()
                    stack.append(maps[token](b, a))
                else:
                    stack.append(int(token))
            return stack[-1]

        s = s.replace(" ","")
        res = in_to_suffix(s)
        return evalRPN(res)

方法二:栈

class Solution:
    def calculate(self, s: str) -> int:
        stack = []
        i = 0
        while i < len(s):
            if s[i].isdigit():
                tmp = 0
                while i < len(s) and s[i].isdigit():
                    tmp = tmp * 10 + int(s[i])
                    i += 1
                stack.append(tmp)
                # 如果栈中有乘除,先算出来
                while len(stack) > 1 and stack[-2] in {"*", "/"}:
                    stack.pop()
                    opt = stack.pop()
                    if opt == "*":
                        stack.append(stack.pop() * tmp)
                    else:
                        stack.append(stack.pop() // tmp)
            elif s[i] in { "*", "/", "+", "-"}:
                stack.append(s[i])
                i += 1
            else:
                 i += 1
        res = 0
        sign = 1
        for t in stack:
            if t == "+":
                sign = 1
            elif t == "-":
                sign = -1
            else:
                res += sign * t
        return res

 

posted @ 2019-10-05 11:03  oldby  阅读(184)  评论(0编辑  收藏  举报