File tree Expand file tree Collapse file tree 1 file changed +44
-11
lines changed
src/main/java/com/thealgorithms/stacks Expand file tree Collapse file tree 1 file changed +44
-11
lines changed Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments