medium
https://leetcode.com/problems/basic-calculator-ii/
mplement 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
思路: - use stack to store number after operation. initialize sign as '+'
- calculating current val = val * 10 + char
- when meet next sign, perform operation of last sign on current number(+,-*,/)
- finally sum up number in stack
eg: 2+33*2
(here) sign = +, val = 33, then sign = *
Complexity: Time O(N) Space O(N)
public int calculate(String s) { if(s == null || s.length() == 0) return 0; Stack<Integer> st = new Stack(); char sign = '+'; int val = 0; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(Character.isDigit(c)){ val = val*10 + (c -'0'); } if((!Character.isDigit(c) && c != ' ') || i == s.length() - 1){ if(sign == '+'){ st.push(val); } if(sign == '-'){ st.push(-val); } if(sign == '*'){ st.push(st.pop()*val); } if(sign == '/'){ st.push(st.pop()/val); } sign = c; val = 0; } } int res = 0; for(Integer i: st){ res += i; } return res; }
No comments:
Post a Comment