方法1: 这道题相对于224来说稍微容易一点,因为不用考虑括号配对问题。思路大致也是使用一个stack,遍历整个string,如果遇到乘除法,直接把答案算出来,然后直接push进stack,整个过程中stack中只保存数字,这些数字最后全部加起来就是答案。具体解释直接看lc官方解答1,写得不错。时间复杂n,空间复杂n。
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int operand = 0;
char operation = '+';
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
operand = operand * 10 + (c - '0');
}
if(!Character.isDigit(c) && c != ' ' || i == s.length()-1){
if(operation == '-'){
stack.push(-operand);
}
if(operation == '+'){
stack.push(operand);
}
if(operation == '*'){
stack.push(stack.pop() * operand);
}
if(operation == '/'){
stack.push(stack.pop() / operand);
}
operation = c;
operand = 0;
}
}
int res = 0;
while(!stack.isEmpty()){
res += stack.pop();
}
return res;
}
}
方法2: 不用stack,所以空间复杂1。这个方法看起来是方法1的优化,并且代码上变化也不大,但是其实逻辑上还是挺难理解的,我暂时不要求自己掌握。具体解释直接看lc官方解答2.
class Solution {
public int calculate(String s) {
if (s == null || s.isEmpty()) return 0;
int length = s.length();
int currentNumber = 0, lastNumber = 0, result = 0;
char operation = '+';
for (int i = 0; i < length; i++) {
char currentChar = s.charAt(i);
if (Character.isDigit(currentChar)) {
currentNumber = (currentNumber * 10) + (currentChar - '0');
}
if (!Character.isDigit(currentChar) && !Character.isWhitespace(currentChar) || i == length - 1) {
if (operation == '+' || operation == '-') {
result += lastNumber;
lastNumber = (operation == '+') ? currentNumber : -currentNumber;
} else if (operation == '*') {
lastNumber = lastNumber * currentNumber;
} else if (operation == '/') {
lastNumber = lastNumber / currentNumber;
}
operation = currentChar;
currentNumber = 0;
}
}
result += lastNumber;
return result;
}
}
总结:
- 无