LC.P227[基本计算器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
class Solution {
public int calculate(String s) {
char[] cs = s.toCharArray();
int n = cs.length, num = 0;
Deque<Integer> stack = new ArrayDeque<>();
char sign = '+';
for (int i = 0; i < n; ++i) {
char c = cs[i];
// 数字
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;
}
}
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop();
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$