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

leetcode-224-基本计算器

时间:2019-10-04 20:51:54      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:return   nbsp   span   val   inf   表达式   中缀   中缀表达式   while   

题目描述:

技术图片

 

 方法一:中缀表达式转后缀表达式,再用150题方法求解

class Solution:
    def calculate(self, s: str) -> int:
        tokens = self.infix_to_suffix(s)
        result = self.evalRPN(tokens)
        return result
            
    def infix_to_suffix(self,s):
        s = re.split((\W),s)
        result = []
        stack = []
        op_priority = {*:2,
                      /:2,
                      %:2,
                      +:1,
                      -:1}
        for i in s:
            if i == ‘‘ or i ==  :
                continue
            if i == (:
                stack.append(i)
            elif i == ):
                while stack[-1] != (:
                    result.append(stack.pop())
                stack.pop()
            elif i in op_priority.keys():
                while stack and stack[-1] in op_priority.keys() and op_priority[i] <= op_priority[stack[-1]]:
                    result.append(stack.pop())
                stack.append(i)
            else:
                result.append(int(i))
        while stack:
            result.append(stack.pop())
        return result
    
    def evalRPN(self, tokens):
        f1 = lambda a,b:a+b
        f2 = lambda a,b: a - b
        f3 = lambda a,b: a*b
        f4 = lambda a,b: int(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:
                token = int(token)
                stack.append(token)
        return stack[-1] 

方法二:单栈

class Solution:
    def calculate(self, s: str) -> int:
        res = 0
        stack = []
        sign = 1
        i = 0
        n = len(s)
        while i < n:
            if s[i] == " ":
                i += 1
            elif s[i] == "-":
                sign = -1
                i += 1
            elif s[i] == "+":
                sign = 1
                i += 1
            elif s[i] == "(":
                stack.append(res)
                stack.append(sign)
                res = 0
                sign = 1
                i += 1
            elif s[i] == ")":
                # print(stack)
                res = res * stack.pop() + stack.pop()
                i += 1
            elif s[i].isdigit():
                tmp = int(s[i])
                i += 1
                while i < n and s[i].isdigit():
                    tmp = tmp * 10 + int(s[i])
                    i += 1
                res += tmp * sign
        return res

方法三:双栈 操作符栈+数字栈

leetcode-224-基本计算器

标签:return   nbsp   span   val   inf   表达式   中缀   中缀表达式   while   

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

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