牛客网

package myTest;
import java.util.*;
public class Stacktest {
	public static void main(String[]args){
     Solution e=new Solution();
     String[]token= new String[]{"6","3","/","4","+","2","-"};
//     String[]token= new String[]{ "0","3","/"};
     int x=e.evalRPN(token);
     System.out.println(x);
//     String xx=e.evalRPN(token);
//     System.out.println(xx);
}
}

class Solution {
	 public int evalRPN(String[] tokens) {
		    Stack<String>myStack=new Stack<String>();//输出整个格式
		    Stack<Integer>myStack2=new Stack<Integer>();   //输出最后结果
		    String target="";
		    String pre="";
		    int total=0;
		    for(int i=0;i<tokens.length;i++){
		        if(!tokens[i].equals("+")&&!tokens[i].equals("-")&&!tokens[i].equals("*")&&!tokens[i].equals("/")){
		            myStack.push(tokens[i]);
		            myStack2.push(Integer.valueOf(tokens[i]));
		        }
		        else{ String b=myStack.pop();
		              String a=myStack.pop();
		              int bb=Integer.valueOf(myStack2.pop());
		              int aa=Integer.valueOf(myStack2.pop());
		              myStack.push("("+a+tokens[i]+b+")");
		              total = jisuan(aa,tokens[i],bb);
		              myStack2.push(total);
		        } 
		    }
		    return myStack2.pop();
		        
		        
		    }
    public int jisuan(int a,String ts,int b){
        if(ts=="+") return a+b;
        else if(ts=="-") return a-b;
              else  if(ts=="*") return a*b;
                  else if(ts=="/") return a/b;
        return 0;
    }
    
    
    
}

猜你喜欢

转载自blog.csdn.net/weixin_36564655/article/details/79825986