LeetCode: Valid Parentheses

LeetCode: Valid Parentheses

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

/**
* Description
*
* @author hzhou
*/
public class ValidParentheses {
public boolean isValid(String s) {
if (s == null || s.isEmpty()) {
return true;
}
s = s.trim();
if (s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (isPre(c)) {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char t = stack.pop();
if (c != findPair(t)) {
return false;
}
}
}
return stack.isEmpty();
}
private char findPair(char c) {
switch (c) {
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
default:
return 0;
}
}
private boolean isPre(char c) {
return c == '(' || c == '{' || c == '[';
}
}