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.
01 public boolean isValid(String s) {
02 char[] str=s.toCharArray();
03 if(str.length%2==1)
04 return false;
05 char [] stack =new char[str.length];
06 int index=0;
07 for(int i=0;i<str.length;i++)
08 {
09 char curr=str[i];
10 if(curr=='(' || curr=='[' || curr=='{')
11 {
12 stack[index++]=str[i];
13 }
14 else
15 {
16 if(index==0)
17 return false;
18 else
19 {
20 char left=stack[--index];
21 if(!isMatch (left,curr))
22 return false;
23 }
24 }
25 }
26 if(index==0)
27 return true;
28 else
29 return false;
30 }
31 public boolean isMatch(char left, char right)
32 {
33 if(left=='(' && right == ')'|| left=='[' && right==']' || left=='{' && right=='}')
34 return true;
35 else
36 return false;
37 }
02 char[] str=s.toCharArray();
03 if(str.length%2==1)
04 return false;
05 char [] stack =new char[str.length];
06 int index=0;
07 for(int i=0;i<str.length;i++)
08 {
09 char curr=str[i];
10 if(curr=='(' || curr=='[' || curr=='{')
11 {
12 stack[index++]=str[i];
13 }
14 else
15 {
16 if(index==0)
17 return false;
18 else
19 {
20 char left=stack[--index];
21 if(!isMatch (left,curr))
22 return false;
23 }
24 }
25 }
26 if(index==0)
27 return true;
28 else
29 return false;
30 }
31 public boolean isMatch(char left, char right)
32 {
33 if(left=='(' && right == ')'|| left=='[' && right==']' || left=='{' && right=='}')
34 return true;
35 else
36 return false;
37 }
没有评论:
发表评论