LC.P224[基本计算器]

方法一:栈

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
36
37
38
39
40
41
42
class Solution {

int i, n;
char[] cs;

public int calculate(String s) {
cs = s.toCharArray();
n = cs.length;
return cal();
}

private int cal() {
int num = 0;
char sign = '+';
Deque<Integer> stack = new ArrayDeque<>();
for (; i < n; ++i) {
char c = cs[i];
if (c == '(') { // 开始递归
++i;
num = cal();
} else if (c >= '0' && c <= '9') { // 数字
num = num * 10 + (c - '0');
}
if (!(c >= '0' && c <= '9') && c != ' ' || i == n - 1) {
// 符号
switch (sign) {
case '+' -> stack.push(num);
case '-' -> stack.push(-num);
case '*' -> stack.push(stack.pop() * num);
case '/' -> stack.push(stack.pop() / num);
}
sign = c;
num = 0;
}
// 结束递归
if (c == ')') break;
}
int ans = 0;
while (!stack.isEmpty()) ans += stack.pop();
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$