阿里编程逆波兰表达式有人ac吗
只有40%哪里有问题啊 import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { ArrayList<Integer> inputs = new ArrayList<Integer>(); Scanner in = new Scanner(System.in); String line = in.nextLine(); if(line != null && !line.isEmpty()) { int res = resolve(line.trim()); System.out.println(String.valueOf(res)); } } // write your code here public static int resolve(String expr) { StringBuffer sb = new StringBuffer(); for(int i=0;i<expr.length();i++){ if(expr.charAt(i)==' '){ continue; }else{ sb.append(expr.charAt(i)); //sb.append(" "); } } String test = sb.toString(); //String[] sp=test.split(" "); char[] chas = test.toCharArray(); Stack<Integer> stack = new Stack<Integer>(); for(int i=0;i<chas.length;i++){ if(chas[i]=='*'){ if(stack.size()<2){ return -1; } int m1=stack.pop(); int m2=stack.pop(); int m = m1*m2; stack.push(m); }else if(chas[i]=='+'){ if(stack.size()<2){ return -1; } int m1=stack.pop(); int m2=stack.pop(); int m = m1+m2; stack.push(m); }else if(chas[i]=='^'){ int x = stack.pop(); x=x+1; stack.push(x); }else{ String cs = chas[i]+""; int value = Integer.valueOf(cs); if(stack.size()==16){ return -2; } stack.push(value); } } return stack.peek(); } }
#阿里巴巴#