原题链接在这里:https://leetcode.com/problems/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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
题解:
与Basic Calculator类似。
扫一遍string, 遇到数字计算数字。遇到符号位时先把之前的符号位和当前的数字计算压入stack, 再更改sign, 清空num.
若之前的sign是'*'或者'/'就先pop()出来一个数字与当前数字做相应运算.
最后把stack中逐个数字加入res中.
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public int calculate(String s) { 3 if(s == null || s.length() == 0){ 4 throw new IllegalArgumentException("Invalid input string."); 5 } 6 7 char sign = '+'; 8 int cur = 0; 9 Stack<Integer> stk = new Stack<Integer>(); 10 for(int i = 0; i<s.length(); i++){ 11 if(Character.isDigit(s.charAt(i))){ 12 cur = cur*10 + (int)(s.charAt(i)-'0'); 13 } 14 15 if((!Character.isDigit(s.charAt(i)) && s.charAt(i)!=' ') || i==s.length()-1){ 16 if(sign == '-'){ 17 stk.push(-cur); 18 }else if(sign == '+'){ 19 stk.push(cur); 20 }else if(sign == '*'){ 21 stk.push(stk.pop()*cur); 22 }else if(sign == '/'){ 23 stk.push(stk.pop()/cur); 24 } 25 sign = s.charAt(i); 26 cur = 0; 27 } 28 } 29 30 int res = 0; 31 for(int num : stk){ 32 res += num; 33 } 34 return res; 35 } 36 }