-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay17.java
More file actions
34 lines (29 loc) · 1.19 KB
/
Day17.java
File metadata and controls
34 lines (29 loc) · 1.19 KB
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
import java.util.Stack;
public class Day17 {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (!stack.isEmpty() && isMatchingPair(stack.peek(), ch)) {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
private boolean isMatchingPair(char open, char close) {
return (open == '(' && close == ')') || (open == '{' && close == '}') || (open == '[' && close == ']');
}
public static void main(String[] args) {
Day17 validator = new Day17();
// Example usage
String testString1 = "()[]{}";
String testString2 = "([)]";
String testString3 = "{[]}";
System.out.println("Is '" + testString1 + "' valid? " + validator.isValid(testString1));
System.out.println("Is '" + testString2 + "' valid? " + validator.isValid(testString2));
System.out.println("Is '" + testString3 + "' valid? " + validator.isValid(testString3));
}
}