Time Limit Exceeded


  • 0
    O

    My code takes O(n) but i still get time limit exceeded. Here is the code

    	Stack<Integer> S = new Stack<Integer>();
    		for (int i = 0 ; i< a.length; i++)
    		{
    			
    			try
    			{
    			int c = Integer.parseInt(a[i]);
    			System.out.println(c);
    			S.push(c);
    			}
    			
    			catch(NumberFormatException e)
    			{
    				int x = S.pop();
    				int y = S.pop();
    				System.out.println(a[i]);
    				switch(a[i]){
    				case "+":
    				S.push(x+y);
    				break;
    				case "-":
    				S.push(x-y);
    				break;
    				case "*":
    				S.push(x*y);
    				break;
    				case "/":
    				S.push(y/x);
    				break;
    				
    				}	
    				
    			}
    			
    			
    			
    			
    			
    		}
    		
    		int s = S.pop();
    		
    		System.out.println(s);
    		
    		return s;

  • 0
    S

    Do not do any system out in your code when you submit. This will lead to unexpected result.


  • 0
    F

    in switch-case you may want to use char, instead of String. i.e. use case '+': instead of case "+":. (similar for other notations). Also, as noted, avoid printing any content in the program, as it may be taken as a final result.


  • 1
    H

    Remove System.out.println(a[i]); that takes a lot of resources from your memory.


  • 0
    G

    this works only for single digit numbers though. How do you do 15+22*43/17?


Log in to reply
 

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