public class Solution {
public int calculate(String s) {
Stack<String> stack = new Stack<String>();
s = s.replace(" ", "");
int length = s.length();
int index = 0;
if (s.charAt(0) <= '9' && s.charAt(0) >= '0')
stack.push("+");
while (index < length) {
char ch = s.charAt(index);
if (ch > '9' || ch < '0') {
if (ch == '+' || ch == '-') {
stack.push(String.valueOf(ch));
index ++;
} else {
int first = Integer.valueOf(stack.pop());
int tmp = index;
index = helper(s, index + 1);
int second = Integer.valueOf(s.substring(tmp + 1, index));
if (ch == '*') {
stack.push(String.valueOf(first * second));
} else {
stack.push(String.valueOf(first / second));
}
}
} else {
int tmp = index;
index = helper(s, index + 1);
stack.push(s.substring(tmp, index));
}
}
int result = 0;
while (!stack.isEmpty()) {
int tmp = Integer.valueOf(stack.pop());
int positive = stack.pop().equals("+") ? 1 : -1;
result += tmp * positive;
}
return result;
}
public int helper(String s, int index) {
while(index < s.length() && s.charAt(index) <= '9' && s.charAt(index) >= '0') {
index ++;
}
return index;
}
}