-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday2.java
More file actions
33 lines (31 loc) · 1.06 KB
/
Copy pathday2.java
File metadata and controls
33 lines (31 loc) · 1.06 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
import java.util.Stack;
public class day2 {
public static void main(String[] args){
String test1 = "()";
String test2 = "[)";
String test3 = "{[()]}";
String test4 = "{[(])}";
Stack<Character> stack = new Stack<>();
boolean flag = false;
for (char c : test3.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (stack.isEmpty()) {
flag = false; // No opening bracket to match
break;
}
char top = stack.pop();
if (!((top == '(' && c == ')') || (top == '[' && c == ']') || (top == '{' && c == '}'))) {
flag = false; // Mismatch found
break;
}
}
}
// Check if the stack is empty after processing all characters
if (!stack.isEmpty()) {
flag = false;
}
System.out.println("Flag: " + flag);
}
}