-
Notifications
You must be signed in to change notification settings - Fork 6
/
ValidParentheses.java
66 lines (64 loc) · 1.89 KB
/
ValidParentheses.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package io.ziheng.stack.leetcode;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* LeetCode 20. Valid Parentheses
* https://leetcode.com/problems/valid-parentheses/
*/
public class ValidParentheses {
public static void main(String[] args) {
ValidParentheses obj = new ValidParentheses();
String s = "{}";
System.out.println(
obj.isValid(s)
);
}
public boolean isValid(String s) {
// 暴力法
// return isValidBruteForce(s);
// 使用栈
return isValidWithStack(s);
}
private boolean isValidWithStack(String s) {
if (s == null || s.length() == 0) {
return true;
}
Deque<Character> stack = new ArrayDeque<Character>();
for (char c: s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char topChar = stack.pop();
if ((c == ')' && topChar != '(') ||
(c == ']' && topChar != '[') ||
(c == '}' && topChar != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
private boolean isValidBruteForce(String s) {
if (s == null || s.length() == 0) {
return true;
}
while (s.indexOf("()") != -1
|| s.indexOf("[]") != -1
|| s.indexOf("{}") != -1) {
if (s.indexOf("()") != -1) {
s = s.replace("()", "");
} else if (s.indexOf("[]") != -1) {
s = s.replace("[]", "");
} else if (s.indexOf("{}") != -1) {
s = s.replace("{}", "");
} else {
// ...
}
}
return s.length() == 0;
}
}
/* EOF */