[抄题]: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里存着
[输入量]:空: 正常状况:特大:特小:程序里处理到的特殊状况:异常状况(不合法不合理的输入):
[画图]:
[一刷]:
[二刷]:
由于用的是以前的operator,i==len-1最后一位,必需要压进去强制性计算了
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
[复杂度]: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; } }