-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode20.java
37 lines (35 loc) · 1.12 KB
/
LeetCode20.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
import java.util.Stack;
public class LeetCode20 {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}
// Stolen solution
// public boolean isValid(String s) {
// int i = -1;
// char[] stack = new char[s.length()];
// for (char ch : s.toCharArray()) {
// if (ch == '(' || ch == '{' || ch == '[')
// stack[++i] = ch;
// else {
// if (i >= 0
// && ((stack[i] == '(' && ch == ')')
// || (stack[i] == '{' && ch == '}')
// || (stack[i] == '[' && ch == ']')))
// i--;
// else
// return false;
// }
// }
// return i == -1;