-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathS3Balancedbrackets.java
More file actions
49 lines (43 loc) · 1.49 KB
/
Copy pathS3Balancedbrackets.java
File metadata and controls
49 lines (43 loc) · 1.49 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
public class S3Balancedbrackets {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
Stack<Character> st = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
st.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
boolean val = handleclosing(st, ch); // Pass the correct closing character
if (!val) {
System.out.println(val);
return;
}
}
}
if (st.isEmpty()) {
System.out.println(true);
} else {
System.out.println(false);
}
}
public static boolean handleclosing(Stack<Character> st, char corresoch) {
if (st.isEmpty()) {
return false;
} else {
char openBracket = getCorrespondingOpening(corresoch);
if (st.peek() != openBracket) {
return false;
}
st.pop();
return true;
}
}
public static char getCorrespondingOpening(char closing) {
if (closing == ')') return '(';
if (closing == '}') return '{';
if (closing == ']') return '[';
return '\0'; // Return a default value or handle error
}
}