Why time limited exceed?


  • 0
    M
    public static int evalRPN(String[] tokens) {
            if(tokens==null||tokens.length==0)
            return 0;
            Stack<Integer> stack=new Stack<Integer>();
            int res=0;
            for(int i=0;i<tokens.length;i++){
            	
            	boolean isNum = tokens[i].matches("[0-9]+")||tokens[i].matches("-[0-9]+");
            
                if(isNum){
                   stack.push(Integer.parseInt(tokens[i]));
                }
                if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")){
                    int second=stack.pop();
                    int first=stack.pop();
                    if(tokens[i].equals("+")) res=first+second;
                    if(tokens[i].equals("-")) res=first-second;
                    if(tokens[i].equals("*")) res=first*second;
                    if(tokens[i].equals("/")) res=first/second;
                     stack.push(res);     
                }
            }
            
            return res;
            
        }
    I don't know why it's time exceed????

  • 0
    A

    First, tokens[i] could only be either number or operator. You should put "else" but not "if" for the second if statement in your for loop.
    Second, it might be faster if you check the operator one by one using switch-case or if-elseif block first and handle the numbers in default/else block. In this way you do not need to check whether it is a number.


  • 0
    M

    You are right, thank you!


Log in to reply
 

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