File tree Expand file tree Collapse file tree 2 files changed +33
-1
lines changed
src/com/blankj/easy/_0020 Expand file tree Collapse file tree 2 files changed +33
-1
lines changed Original file line number Diff line number Diff line change
1
+ package com .blankj .easy ._020 ;
2
+
3
+ /**
4
+ * @author luojing
5
+ * @description LJSolution
6
+ * @date 2022/07/17
7
+ */
8
+
9
+ public class LJSolution {
10
+ public boolean isValid (String s ) {
11
+ char [] stack = new char [s .length () + 1 ];
12
+ int top = 1 ; //top从1开始,避免--top的数组越界Exception的发生
13
+ for (char c : s .toCharArray ()) {
14
+ if (c == '(' || c == '[' || c == '{' ) {
15
+ stack [top ++] = c ;
16
+ } else if (c == ')' && stack [--top ] != '(' ) {
17
+ return false ;
18
+ } else if (c == ']' && stack [--top ] != '[' ) {
19
+ return false ;
20
+ } else if (c == '}' && stack [--top ] != '{' ) {
21
+ return false ;
22
+ }
23
+ }
24
+ return top == 1 ;
25
+ }
26
+
27
+ public static void main (String [] args ) {
28
+ LJSolution ljSolution = new LJSolution ();
29
+ System .out .println (ljSolution .isValid ("()[]{}({[]})" ));
30
+ System .out .println (ljSolution .isValid ("(])]" ));
31
+ }
32
+ }
Original file line number Diff line number Diff line change @@ -23,7 +23,7 @@ public boolean isValid(String s) {
23
23
return false ;
24
24
}
25
25
}
26
- return top == 1 ;
26
+ return top == 1 ; //防止奇数个括号返回true的情形出现
27
27
}
28
28
29
29
public static void main (String [] args ) {
You can’t perform that action at this time.
0 commit comments