Skip to content

Commit 4e06680

Browse files
add BalancedParentheses
1 parent 7718851 commit 4e06680

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

0 commit comments

Comments
 (0)