224.基本计算器

难度:困难
题目描述:
224.基本计算器_第1张图片
思路总结:这道题解不出的本质原因就是对这种类型的题,栈的作用本质还没理解透彻。比如,当左括号入栈,入的是什么;当遇到右括号,出栈的是什么?出栈以后怎么操作。有这些问题困扰,这种题用栈解法就永远不会得到解决。
题解一:(naive)

class Solution:
    def calculate(self, s: str) -> int:
        #Too young, too simple, sometimes naive。
        res = 0
        mul, operator = 0, '+'
        for c in s:
            if '0'<=c<='9':
                mul = mul * 10 + int(c)
            elif c in ['-', '+']:
                if operator == '+':res += mul
                else:res -= mul
                mul, operator = 0, '+'
                if c == '-':operator='-'
        if operator == '+':res += mul
        else:res -= mul
        return res

题解二:(栈)

class Solution:
    def calculate(self, s: str) -> int:
        op = 1
        i = 0
        num = 0
        stack = []
        while i < len(s):
            if s[i] == ' ':
                i+=1
            elif s[i] == '+':
                op = 1
                i+=1
            elif s[i] == '-':
                op = -1
                i+=1
            elif s[i] == '(':
                stack.append((op, num))
                op, num = 1, 0
                i+=1
            elif s[i] == ')':
                print(stack)
                opt, numb = stack.pop() #获取(之前的
                num = numb + opt * num #加上括号里的和括号之前的
                i+=1
            elif s[i].isdigit():
                tmp = int(s[i])
                i+=1
                while i<len(s) and s[i].isdigit():
                    tmp = tmp * 10 + int(s[i])
                    i+=1
                num += tmp * op
        return num

题解二结果:
在这里插入图片描述

你可能感兴趣的:(朱滕威的面试之路)