Monday, January 12, 2015

Valid Parentheses (LeetCode String)

Question: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Idea: Use a stack to check the pairs.

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public boolean isValid(String s) {  
     Stack<Character> stack=new Stack<Character>();  
     for(int i=0;i<s.length();i++)  
     {  
       char c=s.charAt(i);  
       if(c=='('||c=='{'||c=='[')  
         stack.push(c);  
       else   
       {  
         if(stack.isEmpty())  
           return false;  
         char right=stack.pop();  
         if(c==')'&&right!='(')  
           return false;  
         if(c=='}'&&right!='{')  
           return false;  
         if(c==']'&&right!='[')  
           return false;  
       }  
     }  
     if(stack.isEmpty())  
       return true;  
     else  
       return false;  
   }  
 }  

No comments:

Post a Comment