227. Basic Calculator II 無括號版本計算器

[抄題]:git

Implement a basic calculator to evaluate a simple expression string.算法

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.express

Example 1:數據結構

Input: "3+2*2"
Output: 7

Example 2:ide

Input: " 3/2 "
Output: 1

Example 3:oop

Input: " 3+5 / 2 "
Output: 5

 

 [暴力解法]:優化

時間分析:lua

空間分析:spa

 [優化後]:debug

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

 

[思惟問題]:

覺得要用倆stack,而後加減法待定 先不算,不知道怎麼處理。-放到stack裏啊,stack不就是用來暫存的嗎!

忘了數字若是很長的話,須要這樣進位:num = num*10+s.charAt(i)-'0';

[英文數據結構或算法,爲何不用別的數據結構或算法]:

[一句話思路]:

乘除法直接算,加減法先在stack裏存着

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  1. 能夠不用兩個stack,可是sign符號變量和數字變量c分開,符號運算完後符號重置、數字清零。以避免出錯
  2. 應該這樣寫:Character.isDigit(c),表明Character的一個方法
  3. !c == ''應該寫成不等號啊,腦子別短路

 

[二刷]:

  1. 由於用的是以前的operator,i==len-1最後一位,必需要壓進去強制性計算了

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

  1. 能夠不用兩個stack,可是sign符號變量和數字變量c分開,以避免出錯

[複雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

 

s.charAt(i)若是總是要用,就用c暫時存一下,以避免總是重複寫

 

 [是否頭一次寫此類driver funcion的代碼] :

 [潛臺詞] :

class Solution {
    public int calculate(String s) {
        //corner case
        if (s == null || s.length() == 0) return 0;
        
        //initialization: stack
        Stack<Integer> stack = new Stack<Integer>();
        
        //for loop in 4 cases and number
        //initialize number
        int num = 0;
        char operator = '+';
        for (int i = 0; i < s.length(); i++) {
            //num or not 
            char c = s.charAt(i);
            if (Character.isDigit(s.charAt(i))) {
                num = num * 10 + s.charAt(i) - '0';
                System.out.println("num = " + num);
            }
            if ((!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ') || (i == s.length() - 1)) {
                //calculate in 4 cases, use the previous operator 
                if (operator == '+')
                    stack.push(num);
                if (operator == '-')
                    stack.push(-num);
                if (operator == '*')
                    stack.push(stack.pop() * num);
                if (operator == '/')
                    stack.push(stack.pop() / num);
                
                //reset num and operator
                num = 0;
                operator = s.charAt(i);
            }
        }
        
        
        //sum up all the variables in stack
        int sum = 0;
        while (!stack.isEmpty())
            {System.out.println("stack.peek() = " + stack.peek());
            sum += stack.pop();}
        
        //return
        return sum;
    }
}
View Code
相關文章
相關標籤/搜索