Labuladong-实现基础计算器

224. 基本计算器
227. 基本计算器 II
772. 基本计算器 III

主要借助栈(加减乘除) + 递归(括号)

加一个preSign '+'

即:

+ - 数 直接入栈

* / 借用栈的性质,将计算结果入栈

( ) 使用递归先计算括号内的数,将结果入栈

Basic-Calculator-push-stack-1

227. 基本计算器 II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
char[] cArr = s.toCharArray();
if (cArr.length == 0) return 0;
char sign = '+';
int num = 0;
for (int i = 0; i < cArr.length;) {
if (Character.isDigit(cArr[i])) {
num = num * 10 + (cArr[i] - '0');
}
if ((!Character.isDigit(cArr[i]) && cArr[i] != ' ') || i == cArr.length - 1) {
if (sign == '+') {
stack.push(num);
} else if (sign == '-') {
stack.push(-1 * num);
} else if (sign == '*') {
int peek = stack.pop();
stack.push(peek * num);
} else {
int peek = stack.pop();
stack.push(peek / num);
}
sign = cArr[i];
num = 0;
}
i++;
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}