https://leetcode-cn.com/problems/calculator-lcci/

LeetCode 16.26. 计算器

时间复杂度 O(n)

public int calculate(String s) {
Stack<Integer> nums = new Stack<>();
int i = 0, sum = 0;
while (i < s.length()) {
while (i < s.length() && s.charAt(i) == ' ') {
i++;
}
if (i >= s.length()) break;
char c = s.charAt(i);
if (c == '*' || c == '/' || c == '+' || c == '-') {
i++;
while (s.charAt(i) == ' ') i++;
}
int num = 0;
if (Character.isDigit(s.charAt(i))) {
while (i < s.length() && Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
i++;
}
}
switch (c) {
case '-':
num = -num;
break;
case '*':
num = nums.pop() * num;
break;
case '/':
num = nums.pop() / num;
break;
}
nums.push(num);
}
while (!nums.isEmpty()) {
sum += nums.pop();
}
return sum;
}