Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open(
and closing parentheses)
, the plus+
or minus sign-
,non-negativeintegers and empty spaces.
Example 1:
Input:
"1 + 1"
Output:
2
Example 2:
Input:
" 2-1 + 2 "
Output:
3
Example 3:
Input:
"(1+(4+5+2)-3)+(6+8)"
Output:
23
Note:
eval
built-in library function.class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) return 0;
s = s.trim();
s = s.replaceAll("\\s", "");
int n = s.length();
int ans = 0, sign = 1;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++){
char c = s.charAt(i);
if (Character.isDigit(c)){
int cur = c - '0';
while (i + 1 < n && Character.isDigit(s.charAt(i + 1))){
cur = cur * 10 + (s.charAt(i + 1) - '0');
i++;
}
ans += cur * sign;
}
else if (c == '+'){
sign = 1;
}
else if (c == '-'){
sign = -1;
}
else if (c == '('){
stack.push(ans);
stack.push(sign);
ans = 0;
sign = 1;
}
else if (c == ')'){
ans = ans * stack.pop() + stack.pop();
}
//System.out.println("i: " + i + " ans: " + ans);
}
return ans;
}
}