题解 | 表达式求值
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
import java.util.*;
public class Solution {
/**
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
Stack<Integer> nums = new Stack<>(); // 数字栈
Stack<Character> ops = new Stack<>(); // 运算符栈
int n = s.length();
int i = 0;
while (i < n) {
char c = s.charAt(i);
if (c == ' ') { // 跳过空格
i++;
continue;
}
if (Character.isDigit(c)) {
// 读完整的数字
int num = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
num = num * 10 + (s.charAt(i) - '0');
i++;
}
nums.push(num);
continue; // 注意这里不能 i++,因为已经在 while 里前进
}
if (c == '(') {
ops.push(c);
i++;
} else if (c == ')') {
// 计算直到遇到左括号
while (!ops.isEmpty() && ops.peek() != '(') {
calc(nums, ops);
}
ops.pop(); // 弹出 '('
i++;
} else { // 运算符 + - *
while (!ops.isEmpty() && ops.peek() != '('
&& priority(ops.peek()) >= priority(c)) {
calc(nums, ops);
}
ops.push(c);
i++;
}
}
// 处理剩余运算符
while (!ops.isEmpty()) {
calc(nums, ops);
}
return nums.pop();
}
// 计算一次
private void calc(Stack<Integer> nums, Stack<Character> ops) {
int b = nums.pop();
int a = nums.pop();
char op = ops.pop();
int res = 0;
if (op == '+') res = a + b;
else if (op == '-') res = a - b;
else if (op == '*') res = a * b;
nums.push(res);
}
// 运算符优先级
private int priority(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*') return 2;
return 0;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.solve("2+3*4")); // 14
System.out.println(s.solve("(2+3)*4")); // 20
System.out.println(s.solve("100-50*2")); // 0
System.out.println(s.solve("((1+2)*3-4)*5"));// 35
}
}
安克创新 Anker公司福利 782人发布