RPN code working on small inputs but it is being judged as wrong for large input,Can some one please review my code?


  • 0
    V
    import java.util.LinkedList;
    import java.util.List;
    
    
    public class ReversePolishNotation {
    	
    	public int evalRPN(String[] tokens) {
          if(tokens.length==0)
    	      return 0;
          List<String> tempList=new LinkedList<String>();
          
          for(String str:tokens){
        	 // System.out.println(str);
        	  tempList.add(str);
        	  if("+".equals(str.trim()) || "-".equals(str.trim()) || "/".equals(str.trim()) || "*".equals(str.trim())){
        		  
        		  int listSize=tempList.size();
        		  
        		  if(listSize>=3){
        			  int a=Integer.parseInt(tempList.get(listSize-3));
        			  int b=Integer.parseInt(tempList.get(listSize-2));
        			  String op=tempList.get(listSize-1);
        			  int tempResult=this.arithResult(a, b, op);
        			  tempList.remove(Integer.toString(a));
        			  tempList.remove(Integer.toString(b));
        			  tempList.remove(op);
        			  tempList.add(Integer.toString(tempResult));
        		  }
        		  else{
        			  System.out.println("wrong input");
        			  return 0;
        		  }
        	  
          }
        }
          
          return Integer.parseInt(tempList.get(0));
    	    
       }
    
       
       public int arithResult(int a, int b,String op){
    	   
    	   if("+".equals(op.trim()))  return a+b;
    	   if("-".equals(op.trim()))  return a-b;
    	   if("*".equals(op.trim()))  return a*b;
    	   if("/".equals(op.trim()))  return a/b;
    	   return 0;
       }
    
    }

  • 0
    V

    My problem is resolved. There was a small loophole in my code. I was trying to remove the last three elements in a list but I was using List.remove() method which removes the first occurrence of a given element. So if a given element is occurred twice, then it is not going to remove the last element and the code will not work as per logic :).


  • 0
    S

    Yes, I think it is better and safer to remove element by its index rather than the concrete element itself. Also, Why not use switch case?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.