原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-hard/xwsg7t/
解法一(python):
class Solution:
def calculate(self, s: str) -> int:
# 去除空格
s = s.replace(' ', '')
# 栈用于存储操作数
stack = []
current_num = 0
operation = '+'
for i, char in enumerate(s):
# 如果当前字符是数字,则更新当前数字
if char.isdigit():
current_num = current_num * 10 + int(char)
# 如果当前字符是操作符,或者已经到达字符串末尾
if char in '+-*/' or i == len(s) - 1:
if operation == '+':
stack.append(current_num)
elif operation == '-':
stack.append(-current_num)
elif operation == '*':
stack.append(stack.pop() * current_num)
elif operation == '/':
stack.append(int(stack.pop() / current_num))
# 更新操作符和当前数字
operation = char
current_num = 0
# 栈中所有数字的总和即为最终结果
return sum(stack)
思路:
- 去除空格:先去掉字符串中的所有空格。
- 变量初始化:使用一个栈来处理乘除法的优先级。
- 遍历字符串:逐字符遍历字符串,根据字符的类型(数字或操作符)采取不同的操作。
- 处理数字:如果字符是数字,处理可能出现的多位数。
- 处理操作符:如果字符是操作符(
+
,-
,*
,/
),将当前数字和操作符存储到栈中,然后更新当前操作符。 - 最终计算:遍历完字符串后,栈中的所有元素都是已经按优先级处理好的数字和操作符,将它们累加得到最终结果。
解法二(java):
import java.util.Stack;
public class Solution {
public int calculate(String s) {
// 去除空格
s = s.replace(" ", "");
// 栈用于存储操作数
Stack<Integer> stack = new Stack<>();
int currentNum = 0;
char operation = '+';
for (int i = 0; i < s.length(); i++) {
char charAt = s.charAt(i);
// 如果当前字符是数字,则更新当前数字
if (Character.isDigit(charAt)) {
currentNum = currentNum * 10 + (charAt - '0');
}
// 如果当前字符是操作符,或者已经到达字符串末尾
if (!Character.isDigit(charAt) || i == s.length() - 1) {
if (operation == '+') {
stack.push(currentNum);
} else if (operation == '-') {
stack.push(-currentNum);
} else if (operation == '*') {
stack.push(stack.pop() * currentNum);
} else if (operation == '/') {
stack.push(stack.pop() / currentNum);
}
// 更新操作符和当前数字
operation = charAt;
currentNum = 0;
}
}
// 栈中所有数字的总和即为最终结果
int result = 0;
for (int num : stack) {
result += num;
}
return result;
}
}
思路:同解法一