Why Time Limit Exceeded Error?


  • 0
    R
    public class Solution {
         public static int evalRPN(String[] tokens) {
    	        Stack<Integer> stack=new Stack<Integer>();
    	        if(tokens==null)
    	            return 0;
    	        
    	            int result=0;
    	            for(int i=0;i<tokens.length;i++){
    	                if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/"){
    	                    int second=stack.pop();
    	                    int first=stack.pop();
    	                    if(tokens[i]=="+")
    	                      stack.push(first+second);
    	                    else if(tokens[i]=="-")
    	                        stack.push(first-second);
    	                    else if(tokens[i]=="*")
    	                        stack.push(first*second);
    	                    else
    	                        stack.push(first/second);
    	                }
    	                else{
    	                   try{
    	                    stack.push(Integer.parseInt(tokens[i]));
    	                	}
    	                	catch(NumberFormatException e){
    	                		System.out.println("This is not a number");
    	                	}
    	                }
    	            }
    	            return stack.peek();
    	        
    	   }
    }
    

    Last executed input is very long, I can not past it over here because Maximum length is 8000 characters


  • 0
    M
    • Try using int instead of class Integer.
    • In this Q no need to use try catch to check for other characters. (Not a Req)

Log in to reply
 

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