Valid Parentheses

Valid Parentheses 

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 class Solution {
 2    public boolean isValid(String s) {
 3         if(s.length() % 2 == 1)//个数为奇数返回false
 4             return false;
 5         char stack[] = new char[s.length() / 2];
 6 //        boolean isValid = true;
 7         int top = -1;//栈顶
 8         stack[++top] = s.charAt(0);
 9         
10         for(int i = 1; i < s.length(); i++){//遍历完成
11             
12             if('(' == s.charAt(i) || '[' == s.charAt(i) || '{' == s.charAt(i)){//入栈
13                 if(top >= stack.length - 1)//左括号个数大于右括号个数
14                     return false;
15                 stack[++top] = s.charAt(i);
16             }
17             else{
18                 if(-1 == top){//如果栈已经空了
19                     return false;
20                 }
21                 char temp = stack[top--];//出栈
22                 switch(s.charAt(i)){
23                     case ')':
24                         if(temp != '(')
25                             return false;
26                         break;
27                     case ']':
28                         if(temp != '[')
29                             return false;
30                         break;
31                     case '}':
32                         if(temp != '{')
33                             return false;
34                 }
35             }
36         }
37         if(-1 == top)//栈为空
38             return true;
39         return false;//栈不空
40     }
41 }

 

posted on 2014-11-11 20:53  luckygxf  阅读(188)  评论(0编辑  收藏  举报

导航