题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.Scanner; import java.util.*; public class Main { //用hashMap操作加快查询速度 public static Map<Character,Character> mapInclud = new HashMap<Character,Character>(); static{ mapInclud.put('}','{'); mapInclud.put(']','['); mapInclud.put(')','('); } public static Map<Character,Integer> mapOperation = new HashMap<Character,Integer>(); static{ mapOperation.put('/',2); mapOperation.put('*',2); mapOperation.put('+',1); mapOperation.put('-',1); } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String a = in.nextLine(); out(a); } } //输出方法 public static void out(String s){ Stack stack=new Stack(); char[] cl = s.toCharArray(); int sum= inter(cl); System.out.println(sum); } //栈顶计算 public static void computeResult(Stack<Integer> stack, char op){ String s= op+""; switch(s){ case "-": Integer j= stack.pop(); stack.push(stack.pop()-j); break; case "/": Integer i= stack.pop(); stack.push(stack.pop()/i); break; case "*": stack.push(stack.pop()*stack.pop()); break; case "+": stack.push(stack.pop()+stack.pop()); break; } } //读取字符数组入栈 public static int inter(char[] cl){ Stack<Integer> stackNum = new Stack(); Stack<Character> stackOp = new Stack(); boolean isOP=true; for(int i=0;i<cl.length;i++) { char oo=cl[i]; //当前位置为数字 if(cl[i]>='0' && cl[i]<='9'){ String order=""; while(i<cl.length && cl[i]>='0' && cl[i]<='9'){ order=order+cl[i]; i++; } i--; stackNum.push(Integer.valueOf(order)); isOP=false; } //当前位置为操作符 else if(mapOperation.containsKey(cl[i])){ //当前操作符优先级小于栈顶优先级时 while(!stackOp.empty() && mapOperation.containsKey(stackOp.peek()) && mapOperation.get(stackOp.peek()) > mapOperation.get(cl[i])){ computeResult(stackNum,stackOp.pop()); } //若当前操作符是负号 if(cl[i]=='-' && cl[i+1]>='0' && cl[i+1]<='9'){ i++; if(isOP != true){ stackOp.push('+'); } String order="-"; while( i<cl.length && cl[i]>='0' && cl[i]<='9' ){ order=order+cl[i]; i++; } i--; stackNum.push(Integer.valueOf(order)); isOP=false; } //若不是负号 else{ stackOp.push(cl[i]); isOP=true; } }//当前为右括号 else if(mapInclud.containsKey(cl[i])){ char left=mapInclud.get(cl[i]); while(!stackOp.empty() && !stackNum.empty() && stackOp.peek()!=left){ char c= stackOp.pop(); computeResult(stackNum,c); } stackOp.pop(); if(!stackOp.empty() && stackOp.peek() == '-' ){ char n = stackOp.pop(); stackOp.push('+'); int sum= stackNum.pop(); String order= "-"+sum; stackNum.push(Integer.valueOf(order)); } } //左括号全都压到操作符栈 else{ stackOp.push(cl[i]); isOP=true; } } while(!stackNum.empty() && !stackOp.empty()){ char c= stackOp.pop(); computeResult(stackNum,c); } return stackNum.peek(); } }