Skip to content

Commit 63d93bd

Browse files
Fix switch statement and improve BalancedBrackets implementation
1 parent bd86731 commit 63d93bd

File tree

1 file changed

+44
-11
lines changed

1 file changed

+44
-11
lines changed

src/main/java/com/thealgorithms/stacks/BalancedBrackets.java

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,52 @@ public static boolean isBalanced(String input) {
5555

5656
for (char c : input.toCharArray()) {
5757
switch (c) {
58-
case '(', '[', '{', '<' -> stack.push(c);
59-
case ')', ']', '}', '>' -> {
60-
if (stack.isEmpty() || !isPaired(stack.pop(), c)) {
61-
return false;
62-
}
63-
}
64-
default -> {
65-
// Any non-bracket character makes string invalid
66-
return false;
67-
}
58+
case '(':
59+
case '[':
60+
case '{':
61+
case '<':
62+
stack.push(c);
63+
break;
64+
65+
case ')':
66+
case ']':
67+
case '}':
68+
case '>':
69+
if (stack.isEmpty() || !isPaired(stack.pop(), c)) {
70+
return false;
71+
}
72+
break;
73+
74+
default:
75+
// Any non-bracket character makes string invalid
76+
return false;
6877
}
6978
}
7079

7180
return stack.isEmpty();
7281
}
73-
}
82+
83+
/**
84+
* Optional main method for quick manual testing
85+
*/
86+
public static void main(String[] args) {
87+
String[] tests = {
88+
"()",
89+
"[()]",
90+
"{[<>]}",
91+
"[(])",
92+
"[a+b]",
93+
"",
94+
"<{[()]}>",
95+
"[{<]}>"
96+
};
97+
98+
for (String t : tests) {
99+
try {
100+
System.out.println(t + " -> " + isBalanced(t));
101+
} catch (IllegalArgumentException e) {
102+
System.out.println(t + " -> Error: " + e.getMessage());
103+
}
104+
}
105+
}
106+
}

0 commit comments

Comments
 (0)