Closed congr closed 5 years ago
O(N)
class Solution {
public int calculate(String s) {
s = s.replaceAll(" ", "");
Stack<Integer> st = new Stack();
char op = '+'; // input digits are non negative
int e = 0, b = 0;
while (e < s.length()) {
while (e < s.length() && Character.isDigit(s.charAt(e))) e++;
int n = Integer.parseInt(s.substring(b, e));
if (op == '+') st.push(n);
else if (op == '-') st.push(-1 * n);
else { // * or /
int p = st.pop();
st.push (op == '*' ? p*n : p/n);
}
if(e < s.length()) op = s.charAt(e); // !!!
b = ++e; // e is now at an operator, ++e is needed.
}
int num = 0;
while (!st.isEmpty()) num += st.pop(); // for(int i : stack)
return num;
}
}
https://leetcode.com/problems/basic-calculator-ii/