forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
37 lines (30 loc) · 956 Bytes
/
Solution.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
class Solution {
public boolean isValid(String s) {
if (s == null || s == "") {
return true;
}
char[] chars = s.toCharArray();
int n = chars.length;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < n; ++i) {
char a = chars[i];
if (isLeft(a)) {
stack.push(a);
} else {
if (stack.isEmpty() || !isMatch(stack.pop(), a)) {
return false;
}
}
}
return stack.isEmpty();
}
private boolean isMatch(char a, char b) {
return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}');
}
private boolean isLeft(char a) {
return a == '(' || a == '[' || a == '{';
}
private boolean isRight(char a) {
return a == ')' || a == ']' || a == '}';
}
}