File tree Expand file tree Collapse file tree
main/java/com/examplehub/datastructures/stack
test/java/com/examplehub/datastructures/stack Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .examplehub .datastructures .stack ;
2+
3+ import java .util .Stack ;
4+
5+ public class BalancedParentheses {
6+
7+ /**
8+ * Test if a parentheses expression
9+ *
10+ * @param parenthesesExpr the parentheses expression
11+ * @return {@code true} if given parentheses expression is balanced.å
12+ */
13+ public static boolean isBalanced (String parenthesesExpr ) {
14+ Stack <Character > stack = new Stack <>();
15+ for (int i = 0 ; i < parenthesesExpr .length (); i ++) {
16+ switch (parenthesesExpr .charAt (i )) {
17+ case '(' :
18+ case '[' :
19+ case '{' :
20+ stack .push (parenthesesExpr .charAt (i ));
21+ break ;
22+ case ')' :
23+ case ']' :
24+ case '}' :
25+ if (stack .isEmpty () || !isPaired (stack .pop (), parenthesesExpr .charAt (i ))) {
26+ return false ;
27+ }
28+ }
29+ }
30+ return stack .isEmpty ();
31+ }
32+
33+ /**
34+ * Test if left bracket and right bracket is paired.
35+ *
36+ * @param leftBracket the left bracket.
37+ * @param rightBracket the right bracket.
38+ * @return {@code true} if two brackets are paired.
39+ */
40+ public static boolean isPaired (char leftBracket , char rightBracket ) {
41+ return leftBracket == '(' && rightBracket == ')'
42+ || leftBracket == '[' && rightBracket == ']'
43+ || leftBracket == '{' && rightBracket == '}' ;
44+ }
45+ }
Original file line number Diff line number Diff line change 1+ package com .examplehub .datastructures .stack ;
2+
3+ import org .junit .jupiter .api .Test ;
4+
5+ import static org .junit .jupiter .api .Assertions .*;
6+
7+ class BalancedParenthesesTest {
8+ @ Test
9+ void testIsBalanced () {
10+ assertTrue (BalancedParentheses .isBalanced ("([]{})" ));
11+ assertTrue (BalancedParentheses .isBalanced ("[()]{}{[()()]()}" ));
12+ assertFalse (BalancedParentheses .isBalanced ("[(])" ));
13+ }
14+
15+ @ Test
16+ void testIsPaired () {
17+ assertTrue (BalancedParentheses .isPaired ('[' , ']' ));
18+ assertTrue (BalancedParentheses .isPaired ('(' , ')' ));
19+ assertTrue (BalancedParentheses .isPaired ('{' , '}' ));
20+ assertFalse (BalancedParentheses .isPaired ('(' , '}' ));
21+ }
22+ }
You can’t perform that action at this time.
0 commit comments