-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5.java
42 lines (40 loc) · 1.06 KB
/
Day5.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
38
39
40
41
42
import java.util.Stack;
public class Day5 {
public static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
// push opening bracket on stack
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
}
//pop opening bracket while there is closing
else if (c == ')' || c == '}' || c == ']') {
if (stack.isEmpty() || !isMatchingPair(stack.peek(), c)) {
return false;
}
stack.pop();
}
}
return stack.isEmpty();
}
private static boolean isMatchingPair(char opening, char closing) {
if(opening == '(' && closing == ')') {
return true;
}else if(opening == '{' && closing == '}') {
return true;
}else if(opening == '[' && closing == ']') {
return true;
}else {
return false;
}
}
public static void main(String [] args) {
Day5 day5 = new Day5();
String s ="({[})";
if(day5.isValid(s)) {
System.out.println("true");
}else {
System.out.println("false");
}
}
}