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.

用栈即可。

public class Solution {
    public static boolean isValid(String s) {
         Stack<Character> gt=new Stack<Character>();  
       int i=0;
       
         
       while(i != s.length())  
       {  
           char c =s.charAt(i);  
           if (c != ')' && c != '}' && c != ']')  
           {  
               gt.push(c);  
           }  
           else  
           {  
               if (gt.size() == 0)  
                  return false;  
 
               char pre = gt.lastElement();  
               switch(c)  
               {  
               case ')':  
                   if (pre == '(')  
                     gt.pop();  
                   else   
                     return false;  
                   break;  
                       
               case '}':  
                   if (pre == '{')  
                     gt.pop();  
                   else   
                     return false;  
                   break;  
                     
               case ']':  
                   if (pre == '[')  
                     gt.pop();  
                   else   
                     return false;  
                   break;  
               }  
           }  
           ++i;  
       }  
       if (gt.size() == 0)  
          return true;  
       else return false;  
   }  

}
View Code

 

posted on 2015-06-15 23:55  gone~with~wind  阅读(94)  评论(0编辑  收藏  举报