forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParentheses.java
37 lines (32 loc) · 1.04 KB
/
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
// https://leetcode.com/problems/valid-parentheses/
// T: O(n)
// S: O(n)
import java.util.Set;
import java.util.Stack;
public class ValidParentheses {
private static final Set<Character> CLOSING_BRACES = Set.of(')', ']', '}');
public boolean isValid(String s) {
final Stack<Character> stack = new Stack<>();
char bracket;
for (int i = 0 ; i < s.length() ; i++) {
bracket = s.charAt(i);
if (isClosingBracket(bracket)) {
if (!stack.isEmpty() && areOpposites(stack.peek(), bracket)) {
stack.pop();
} else return false;
} else stack.push(bracket);
}
return stack.isEmpty();
}
private boolean isClosingBracket(char c) {
return CLOSING_BRACES.contains(c);
}
private boolean areOpposites(char left, char right) {
return switch(left) {
case '(' -> right == ')';
case '[' -> right == ']';
case '{' -> right == '}';
default -> false;
};
}
}