-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution.java
31 lines (27 loc) · 955 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
package valid_parentheses;
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i));
} else {
if (s.charAt(i) == ')') {
if (stack.size() == 0 || stack.pop() != '(') {
return false;
}
} else if (s.charAt(i) == '}') {
if (stack.size() == 0 || stack.pop() != '{') {
return false;
}
} else if (s.charAt(i) == ']') {
if (stack.size() == 0 || stack.pop() != '[') {
return false;
}
}
}
}
return stack.size() == 0;
}
}