题目
https://leetcode-cn.com/problems/basic-calculator/
代码
class Solution {
public int calculate(String s) {
LinkedList<Integer> ops = new LinkedList<Integer>();
ops.push(1);
int sign = 1;
int ret = 0;
int n = s.length();
int i = 0;
while (i < n) {
if (s.charAt(i) == ' ') {
i++;
} else if (s.charAt(i) == '+') {
sign = ops.peekLast();
i++;
} else if (s.charAt(i) == '-') {
sign = -ops.peekLast();
i++;
} else if (s.charAt(i) == '(') {
ops.addLast(sign);
i++;
} else if (s.charAt(i) == ')') {
ops.removeLast();
i++;
} else {
long num = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
i++;
}
ret += sign * num;
}
}
return ret;
}
}
复杂度
时间复杂度:O(n),其中 n 为字符串 s 的长度。需要遍历字符串 s 一次,计算表达式的值。
空间复杂度:O(n),其中 n 为字符串 s 的长度。空间复杂度主要取决于栈的空间,栈中的元素数量不超过 n。