码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-227-基本计算器②

时间:2019-10-05 12:59:36      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:pre   for   else   enum   print   rate   val   tac   class   

题目描述:

技术图片

 

 

方法一:中缀转后缀

#!_*_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-基本计算器②

标签:pre   for   else   enum   print   rate   val   tac   class   

原文地址:https://www.cnblogs.com/oldby/p/11624170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!