括号字符串有效性验证

题目:

      

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.

思路:

    考察栈的概念,当遇到'(','[','{',时全部入栈,当遇到')',']','}'时,与栈顶元素进行匹配

 

 1     public static boolean isValid(String s) {
 2         Stack<Character> stack = new Stack<Character>(); 
 3         
 4         if(s != null && s.length() != 0){
 5             char[] charArray = s.toCharArray();
 6             for(char c : charArray){
 7                 if(c == '(' || c == '[' || c == '{'){
 8                     stack.push(c);
 9                 }else if(c == ')' || c == ']' || c == '}'){
10                     if(stack.empty())
11                         return false;
12                     else{
13                         char temp = stack.pop();
14                         int val = c - temp;
15                         if(!(val == 1 || val == 2)){//匹配括号的字符数值差值只有1和2两种可能
16                             return false;
17                         }
18                             
19                     }
20                 }else{
21                     return false;
22                 }
23             }
24         }else
25             return false;
26         if(stack.isEmpty())
27            return true;
28         else
29             return false;
30     }

 

posted @ 2016-11-21 19:16  music180  阅读(380)  评论(0编辑  收藏  举报