题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
可能是自己目前做题比较少,不太熟练,一道标为简单的题,调试了很多遍才成功;中途自己的方法遇到的坑,一方面有负数的处理,到底是减号还是负号,我是在符号前面加个0,让负号变成减号;另一方面主要是细节方面,很容易忽略而导致错误。import java.util.HashMap; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { // TODO 自动生成的方法存根 Scanner sc = new Scanner(System.in); HashMap<String,Integer> map = new HashMap<String,Integer>(); map.put("+",1); map.put("-",1); map.put("*",2); map.put("/",2); map.put("(", 0); while(sc.hasNext()) { Stack<Integer> st1 = new Stack<Integer>(); Stack<String> st2 = new Stack<String>(); String str = sc.nextLine(); //负数变成0-正数 for(int i = 0;i < str.length();i++) { if(str.charAt(i) == '-') { if(i == 0) { str = '0' + str; continue; } if(str.charAt(i - 1) == ')') { continue; } if(str.charAt(i - 1) < '0' || str.charAt(i - 1) > '9') { str = str.substring(0, i) + '0' + str.substring(i, str.length()); } } } // System.out.println(str); String temp = ""; for(int i = 0;i < str.length();i++) { boolean flag = true; if(str.charAt(i) < '0' || str.charAt(i) > '9') { temp += str.charAt(i); flag = false; } if(str.charAt(i) >= '0' && str.charAt(i) <= '9') { temp += str.charAt(i); if(i < str.length() - 1) { if(str.charAt(i + 1) >= '0' && str.charAt(i + 1) <= '9') { continue; } } } int num = 0; if(flag) { num = Integer.parseInt(temp); st1.push(num); temp = ""; continue; } if(st2.size() == 0) { st2.push(temp); temp = ""; continue; } if(temp.equals("(")) { st2.push(temp); temp = ""; continue; } if(temp.equals(")")) { while(!st2.peek().equals("(")) { int num2 = st1.pop(); int num1 = st1.pop(); String fuhao = st2.pop(); switch(fuhao) { case "+" : st1.push(num1 + num2); break; case "-" : st1.push(num1 - num2); break; case "*" : st1.push(num1 * num2); break; case "/" : st1.push(num1 / num2); break; } } st2.pop(); temp = ""; continue; } if(map.get(temp) > map.get(st2.peek())) { st2.push(temp); temp = ""; continue; }else { while(st2.size() != 0 && map.get(temp) <= map.get(st2.peek())) { int num2 = st1.pop(); int num1 = st1.pop(); String fuhao = st2.pop(); switch(fuhao) { case "+" : st1.push(num1 + num2); break; case "-" : st1.push(num1 - num2); break; case "*" : st1.push(num1 * num2); break; case "/" : st1.push(num1 / num2); break; } if(st2.size() == 0) { break; } if(st2.peek().equals("(")) { break; } } st2.push(temp); temp = ""; continue; } } int nn = st2.size(); for(int i = 0;i < nn;i++) { int num2 = st1.pop(); int num1 = st1.pop(); String fuhao = st2.pop(); switch(fuhao) { case "+" : st1.push(num1 + num2); break; case "-" : st1.push(num1 - num2); break; case "*" : st1.push(num1 * num2); break; case "/" : st1.push(num1 / num2); break; } } System.out.println(st1.pop()); } } }