Simple Java Solution - Includes a string length check


  • 2
    K
    public boolean isValid(String s) {
    
         if(s.length() % 2 == 1)
            return false;
         
         Stack<Character> stack = new Stack<Character>();
    	 for(int i = 0; i < s.length(); i++)
    	 {
    		if(s.charAt(i) == '(')
    		{
    			stack.push(')');
    		}
    		else if(s.charAt(i) == '{')
    		{
    			stack.push('}');
    		}
    		else if(s.charAt(i) == '[')
    		{
    			stack.push(']');
    		}
    		else if(stack.isEmpty() || stack.pop() != s.charAt(i))
    			return false;
    	 }
    	 return stack.isEmpty();
    }
    

    The solution is similar to the other solutions but just includes a string length check that would return false if the string has an odd length. This avoids extraneous calculations.


Log in to reply
 

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