Skip to main content

Basic Calculator II

描述​

TODO

分析​

TODO

代码​

栈​

# Basic Calculator II
# Time complexity: O(n)
# Space complexity: O(n)
class Solution:
def calculate(self, s: str) -> int:
N = len(s)
stk = []
n = 0 # current number
op = '+' # current operation
for i in range(N):
ch = s[i] # current char
if ch.isdigit():
n = (n * 10) + (ord(ch) - ord('0'))
if self.isOp(ch) or i == N - 1:
if op == '-':
stk.append(-n)
elif op == '+':
stk.append(n)
elif op == '*':
top = stk.pop()
stk.append(top * n)
elif op == '/':
top = stk.pop()
stk.append(int(top / n))
op = ch
n = 0
result = 0
while stk:
result += stk.pop()
return result

def isOp(self, ch: str) -> bool:
return ch in {'+', '-', '*', '/'}

上面的代码里有个小技巧,n 和 op初始化为 0 和 +,相当于在表达式前面插入了 0+,帮助简化代码。

优化到常量空间​

上面的代码,可以稍作优化,把栈消除掉。

// Time complexity: O(n)
// Space complexity: O(1)
class Solution {
public int calculate(String s) {
final int N = s.length();
int n = 0; // current number
int last = 0; // last number
int result = 0;
char op = '+'; // current operation
for (int i = 0; i < N; i++) {
char ch = s.charAt(i); // current char
if (Character.isDigit(ch)) {
n = (n * 10) + (ch - '0');
} else if (isOp(ch) || i == N - 1) {
if (op == '+' || op == '-') {
result += last;
last = op == '+' ? n : -n;
stk.push(-n);
} else if (op == '*') {
last *= n;
} else if (op == '/') {
last /= n;
}
op = ch;
n = 0;
}
}
result += last;
return result;
}

private boolean isOp(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
}