實現基本計算器求值,字符串包含非負整數、+ - * /、空格。整數除法向零截斷。不使用 eval。
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
* 和 /,將乘除算式即時計算並壓入列表,+ - 直接壓入操作數與運算符。+ - 從左到右順序計算。public class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) return 0;
LinkedList nums = new LinkedList<>();
char op = '+'; // 上一個運算符,初始視為 '+'
int cur = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
cur = cur * 10 + (c - '0');
}
if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
switch (op) {
case '+': nums.addLast(cur); break;
case '-': nums.addLast(-cur); break;
case '*': nums.addLast(nums.pollLast() * cur); break;
case '/': nums.addLast(nums.pollLast() / cur); break;
}
op = c;
cur = 0;
}
}
int res = 0;
for (int n : nums) res += n;
return res;
}
}
op 保存上一個運算符,當前數字 cur 讀完後根據 op 決定如何入列表。* / 直接與列表尾部數字運算(pollLast),實現優先級提升。O(n),單次掃描 + 列表遍歷。O(n),列表存儲中間操作數。遇到 ( 遞歸調用 calculate 處理子表達式,遇到 ) 返回。需維護索引引用或迭代器。