1. 程式人生 > >【LeetCode】224. Basic Calculator 解題報告(Python)

【LeetCode】224. Basic Calculator 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/basic-calculator/description/

題目描述

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open (

and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

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

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

題目大意

實現一個基本計算器,輸入的是隻含有括號數字加減號的字串。

解題方法

這個題沒有乘除法,也就少了計算優先順序的判斷了。眾所周知,實現計算器需要使用一個棧,來儲存之前的結果,把後面的結果計算出來之後,和棧裡的數字進行操作。

使用了res表示不包括棧裡數字在內的結果,num表示當前操作的數字,sign表示運算子的正負,用棧儲存遇到括號時前面計算好了的結果和運算子。

操作的步驟是:

  • 如果當前是數字,那麼更新計算當前數字;
  • 如果當前是操作符+或者-,那麼需要更新計算當前計算的結果res,並把當前數字num設為0,sign設為正負,重新開始;
  • 如果當前是(,那麼說明後面的小括號裡的內容需要優先計算,所以要把res,sign進棧,更新res和sign為新的開始;
  • 如果當前是),那麼說明當前括號裡的內容已經計算完畢,所以要把之前的結果出棧,然後計算整個式子的結果;
  • 最後,當所有數字結束的時候,需要把結果進行計算,確保結果是正確的。
class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        res, num, sign = 0, 0, 1
        stack = []
        for c in s:
            if c.isdigit():
                num = 10 * num + int(c)
            elif c == "+" or c == "-":
                res = 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 = res + sign * num
                num = 0
                res *= stack.pop()
                res += stack.pop()
        res = res + sign * num
        return res

參考資料

http://www.cnblogs.com/grandyang/p/4570699.html

日期

2018 年 11 月 16 日 —— 週五又來了