-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20. Valid Parentheses
52 lines (45 loc) · 1.33 KB
/
20. 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
49
50
51
52
public class Solution {
// public boolean isValid(String s) {
// Stack<Character> stack = new Stack<Character>();
// for (Character c : s.toCharArray()) {
// if ("({[".contains(String.valueOf(c))) {
// stack.push(c);
// } else {
// if (!stack.isEmpty() && is_valid(stack.peek(), c)) {
// stack.pop();
// } else {
// return false;
// }
// }
// }
// return stack.isEmpty();
// }
// private boolean is_valid(char c1, char c2) {
// return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')
// || (c1 == '[' && c2 == ']');
// }
public boolean isValid (String s) {
if (s == null || s.length() == 0) {
return false;
}
int count = 0;
int length = s.length();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < length; i++) {
if (!stack.empty() && (is_valid(stack.peek(),s.charAt(i)))) {
stack.pop();
count++;
} else {
stack.push(s.charAt(i));
}
}
if (stack.empty()) {
return count >= 0;
}
return false;
}
private boolean is_valid(char c1, char c2) {
return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')
|| (c1 == '[' && c2 == ']');
}
}