Java solution | 236ms | Running time better than 97% of other Java coders


  • 0
    S

    This is my code. Simple approach to put opening braces on a stack. Whenever a closing brace is encountered, it should be matching with the last opening brace which is on the top of stack. It runs in 236 ms. If it can be improved in any way possible, please let me know.

    public boolean isValid(String s) {
            if(s.length() <= 1) return false;
    
    		Stack<Character> stack = new Stack<Character>();
    		char[] charString = s.toCharArray();
    
    		for(int i=0; i<s.length(); i++)
    		{
    			if(charString[i] == '(' || charString[i] == '{' || charString[i] == '[')
    			{
    				stack.push(charString[i]);
    			}
    
    			else if(charString[i] == ')' || charString[i] == '}' || charString[i] == ']')
    			{
    				try
    				{
    					char last = stack.peek();
    					if((charString[i] == ')' && last == '(') || (charString[i] == '}' && last == '{') || (charString[i] == ']' && last == '['))
    						stack.pop();
    					else
    						return false;
    				}
    				
    				// This exception catches cases like )))((() when starting happens with ending parenthesis.
    				catch(Exception e)
    				{
    					return false;
    				}
    			}
                
                // If I remove this else, my score goes down from 97% to 5%
    			else
    				return false;
    
    		}
    
    		if(stack.size() != 0)
    			return false;
    		else
    			return true;
        }*

Log in to reply
 

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