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-negative integers and empty spaces
.
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the
eval
built-in library function.public class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int num = 0, res = 0, sign = 1;
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') continue;
if (Character.isDigit(s.charAt(i))) {
num *= 10;
num += s.charAt(i) - '0';
} else if (s.charAt(i) == '+') {
res += sign * num;
num = 0;
sign = 1;
} else if (s.charAt(i) == '-') {
res += sign * num;
num = 0;
sign = -1;
} else if (s.charAt(i) == '(') {
stk.push(res);
stk.push(sign);
num = 0;
sign = 1;
res = 0;
} else if (s.charAt(i) == ')') {
res += sign * num;
res *= stk.pop();
res += stk.pop();
num = 0;
}
}
return res + num * sign;
}
}
==================
public class Solution {
public int calculate(String s) {
int res = 0;
if (s == null || s.isEmpty()) return 0;
int cur = 0;
char op = '+';
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') continue;
if (Character.isDigit(s.charAt(i))) {
cur *= 10;
cur += s.charAt(i) - '0';
} else {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
if (op == '+') {
res += cur;
} else {
res -= cur;
}
op = s.charAt(i);
cur = 0;
} else if (s.charAt(i) == '(') {
int k = i + 1;
int left = 1;
while (left != 0) {
if (s.charAt(k) == '(') left++;
if (s.charAt(k) == ')') left--;
k++;
}
int rightBracket = k - 1;
cur = calculate(s.substring(i + 1, rightBracket));
i = rightBracket;
}
}
}
if (op == '+') return res + cur;
else return res - cur;
}
}
没有评论:
发表评论