Google面试题专题9 - leetcode224. Basic Calculator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/84783917

224. Basic Calculator - Hard

百度面试题

题目描述

计算器功能。字符串表达式可能包含:(、)、+、-、非负整数和空格。

例子
Example 1:

Input: “1 + 1”
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: “(1+(4+5+2)-3)+(6+8)”
Output: 23

思想
可能的操作如下:
1)如果是数字,更新当前数字num;其余情况都要重置num=0
2)如果是+/-,更新res = sign * num,并重置num=0,sign=±1;
3)如果是(,后面小括号里的内容需优先计算。所以暂时把之前的res,sign进栈,并重置res=1,sign=1;
4)如果是),之前的结果出栈,计算整个式子。
解法

class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip()
        stack = []
        res = num = 0
        sign = 1
        for c in s:
            if c.isdigit():
                num = num * 10 + ord(c) - 48
            elif c in '+-':
                res += sign * num
                num = 0
                sign = 1 if c == '+' else -1
            elif c == '(':
                stack.append(res)
                stack.append(sign)
                res = 0
                sign = 1
            elif c == ')':
                res += sign * num
                res *= stack.pop()
                res += stack.pop()
                num = 0
        return res + sign * num

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/84783917