题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve(String s) { // write code here /** * 表达式求值 */ //设置优先级 HashMap<Character, Integer> map = new HashMap<>(); map.put('+', 1); map.put('-', 1); map.put('*', 2); Stack<Integer> number = new Stack<>(); Stack<Character> op = new Stack<>(); ArrayList<Character> judge = new ArrayList<>(); judge.add('+'); judge.add('-'); judge.add('*'); judge.add('('); judge.add(')'); int n = s.trim().length(); int i = 0; while (i < n) { char c = s.charAt(i); if (c == '(') { op.push(c); } else if (c == ')') { while (!(op.peek() == '(')) { //计算 number.push(compute(number.pop(), number.pop(), op.pop())); } op.pop(); } else { if (c == '+' || c == '-' || c == '*') { if (op.isEmpty() || op.peek() == '(') { op.push(c); } //优先级高入栈 else if (map.get(c) > map.get(op.peek())) { op.push(c); } else if (map.get(c) <= map.get(op.peek())) { //优先级低,先计算 //计算 number.push(compute(number.pop(), number.pop(), op.pop())); op.push(c); } } else { int num = Integer.parseInt(String.valueOf(c)); if ((i + 1) < n) { //循环读取完整数字 while ((i < n-1) && !judge.contains(s.charAt(i + 1))) { num = num * 10 + Integer.parseInt(String.valueOf(s.charAt(i + 1))); i++; } } number.push(num); } } i++; } while (!(op.isEmpty())) { number.push(compute(number.pop(), number.pop(), op.pop())); } return number.peek(); } public static int compute(int m, int n, char op) { switch (op) { case '+': return m + n; case '-': return n - m; case '*': return m * n; } return 0; } }