227. Basic Calculator II 无括号版本计算器

[抄题]:

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.

Example 1:

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

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

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

 

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩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

 

posted @ 2018-08-03 11:22  苗妙苗  阅读(171)  评论(0编辑  收藏  举报