leetcode-227-基本计算器②

Posted oldby

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于leetcode-227-基本计算器②的主要内容,如果未能解决你的问题,请参考以下文章

leetcode227基本计算器II (Medium)

LeetCode 227. 基本计算器 II

Leetcode 227.基本计算器II

LeetCode227:基本计算器II

LeetCode 227. 基本计算器 (Java)

LeetCode 227. 基本计算器 II