题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (String s) { // write code here char[] chs = s.toCharArray(); Stack<String> s0 = new Stack<>(); // 存放数字 Stack<Character> s1 = new Stack<>(); //存放操作符 char last = ' '; for(int i=0;i<chs.length;i++){ if(isChar(chs[i])){ if(chs[i] == ')'){ char oper; while((oper=s1.pop()) !='(') { int n2 = Integer.valueOf(s0.pop()); int n1 = Integer.valueOf(s0.pop()); int res = operation(n1, n2, oper); s0.push(res+""); } } else if(s1.isEmpty() || s1.peek() =='(' || chs[i] == '(') { s1.push(chs[i]); } else if((!s1.isEmpty() && !isPriority(chs[i], s1.peek()))) { int n2 = Integer.valueOf(s0.pop()); int n1 = Integer.valueOf(s0.pop()); char oper = s1.pop(); int res = operation(n1, n2, oper); s0.push(res+""); s1.push(chs[i]); } else{ s1.push(chs[i]); } } else { if(!isChar(last) && !s0.isEmpty()) { s0.push(s0.pop()+chs[i]); } else { s0.push(chs[i]+""); } } //System.out.println(s0); //System.out.println(s1); //System.out.println("-------------------------------------"); last = chs[i]; } int res=0; while(!s1.empty()) { int n2 = Integer.valueOf(s0.pop()); int n1 = Integer.valueOf(s0.pop()); char oper = s1.pop(); res = operation(n1, n2, oper); s0.push(res+""); } return Integer.valueOf(s0.pop()); } public int getIndex(char c) { if(c == '+') { return 0; } else if(c == '-') { return 1; } else if(c == '*') { return 2; } else { return -1; } } public boolean isPriority(char c1, char c2) { boolean[][] b = {{false, false, false},{false, false, false},{true, true, false}}; return b[getIndex(c1)][getIndex(c2)]; } public boolean isChar(char c){ return c == '+' || c == '-' || c == '*' || c == '(' || c == ')'; } public int operation(int a, int b, char c){ //System.out.println(a); //System.out.println(b); int res = Integer.MAX_VALUE; switch(c){ case '+': res = a + b; break; case '-': res = a - b; break; case '*': res = a * b; break; } return res; } }