-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ020_ValidParentheses.java
38 lines (38 loc) · 1.18 KB
/
Q020_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
public class Q020_ValidParentheses {
// Method 1 2ms 100%
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
if (s.length() % 2 == 1) {
return false;
}
char[] stack = new char[s.length()];
int index = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '{' || s.charAt(i) == '[' || s.charAt(i) == '(') {
stack[index] = s.charAt(i);
index++;
} else if (s.charAt(i) == '}'){
if (index == 0 || stack[index - 1] != '{') {
return false;
} else {
index --;
}
} else if (s.charAt(i) == ']'){
if (index == 0 || stack[index - 1] != '[') {
return false;
} else {
index --;
}
} else if (s.charAt(i) == ')'){
if (index == 0 || stack[index - 1] != '(') {
return false;
} else {
index --;
}
}
}
return index == 0;
}
}