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 .
The expression string contains only non-negative integers, +
, -
, *
, /
operators , open (
and closing parentheses )
and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647]
.
Some examples:
"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12
思路:这里跟calculator II很类似,不同的就是加入了括号,括号的处理可以用递归,找到左右边界,递归算出num;
注意后面是处理sign,也就是num之前的符号,+ push(num_, - push(-num), * push(pop() * num), / push(pop/ num);
其余的跟calculator II一模一样,都是把值算好了,丢到stack里面,最后把stack里面的东西sum起来就是答案;
中间找左右两个边界的,跟 1087 Brace Expansion 很类似;
class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0) {
return 0;
}
char sign = '+';
int num = 0;
int res = 0;
Stack<Integer> stack = new Stack<>();
int len = s.length();
for(int i = 0; i < len; i++) {
char c = s.charAt(i);
//取数;
if(Character.isDigit(c)) {
num = num * 10 + c - '0';
}
// 每次是得到当前的运算符,计算之前的数和运算符,然后更新sign为当前的运算符;
// 注意最后一个数字,由于符号总是在数字之前,所以最后一个数字没有办法计算,要单独列出来;
if(!Character.isDigit(c) && c != ' ' || i == len - 1) {
if(c == '(') {
int j = i; int count = 0;
for(; i < len; i++) {
if(s.charAt(i) == '(') {
count++;
}
if(s.charAt(i) == ')') {
count--;
}
if(count == 0) {
break;
}
}
// ( )
// j......i;
num = calculate(s.substring(j + 1, i));
}
if(sign == '+') {
stack.push(num);
} else if(sign == '-') {
stack.push(-num);
} else if(sign == '*') {
stack.push(stack.pop() * num);
} else if(sign == '/') {
stack.push(stack.pop() / num);
}
num = 0;
sign = c;
}
}
for(int val: stack) {
res += val;
}
return res;
}
}