Sunday, January 11, 2015

20. Valid Parentheses Leetcode Java

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.
Solution:
A stack is used to track all the left parentheses that has not been paired. Any current right parentheses has to be paired with the top left parentheses of the stack. If not,then the string is not a valid one.
Because the difference of ASCII code between paired parentheses is either 1 or 2, I use this to check if they are paired or not. I assume all chars of this string are parentheses symbols. 
Time complexity: O(n), Space complexity: O(n)


 public boolean isValid(String s) {  
    if(s==null || s.length()==0) return true;  
    Stack<Character> st=new Stack<Character>();  
    for(int i=0;i<s.length();i++){  
      char temp=s.charAt(i);  
      if(temp=='(' ||temp =='{'|| temp=='[') st.push(temp);  
      else {  
        if(st.isEmpty()) return false;  
        int diff=temp-st.pop();  
        if(diff!=1&&diff!=2) return false;  
      }  
    }  
    return st.isEmpty();  
   }  

No comments:

Post a Comment