Skip to content

Commit b2676e9

Browse files
author
luojing
committed
add 0020 solution
1 parent 79e9778 commit b2676e9

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

src/com/blankj/easy/_0020/Solution.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public boolean isValid(String s) {
2323
return false;
2424
}
2525
}
26-
return top == 1;
26+
return top == 1; //防止奇数个括号返回true的情形出现
2727
}
2828

2929
public static void main(String[] args) {

0 commit comments

Comments
 (0)