-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbalancedExpressions.java
More file actions
101 lines (79 loc) · 1.99 KB
/
balancedExpressions.java
File metadata and controls
101 lines (79 loc) · 1.99 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
public class ExpressionChecker {
private static Character[] openingDelimiters = {'(','{','['};
private static Character[] closingDelimiters = {')','}',']'};
public boolean isBalanced(String expr) throws Exception{
if(expr == null || expr.isEmpty())
throw new Exception("Null or empty parameter");
Stack stack = new Stack();
for(int i = 0; i < expr.length(); i++){
Character c = expr.charAt(i);
if(isClosingDelimiter(c)){
Character pop = stack.pop();
while(!isOpeningDelimiter(pop))
pop = stack.pop();
if(!isPair(pop,c))
return false;
}
else
stack.push(c);
}
while(!stack.isEmpty()){
Character pop = stack.pop();
if(isOpeningDelimiter(pop) || isClosingDelimiter(pop) )
return false;
}
return true;
}
private boolean isPair(Character open, Character close) {
switch(open){
case '(' :
return close.equals(')');
case '{' :
return close.equals('}');
case '[' :
return close.equals(']');
}
return false;
}
private boolean isOpeningDelimiter(Character c) {
for(Character d : openingDelimiters)
if(c.equals(d))
return true;
return false;
}
private boolean isClosingDelimiter(Character c) {
;
for(Character d : closingDelimiters)
if(c.equals(d))
return true;
return false;
}
}
public class ExpressionCheckerTest {
ExpressionChecker target = new ExpressionChecker();
@Test
public void test1() throws Exception {
String expr = "(A+B)+(C+D)";
assertTrue(target.isBalanced(expr));
}
@Test
public void test2() throws Exception {
String expr = "((A+B)+(C+D)";
assertFalse(target.isBalanced(expr));
}
@Test
public void test3() throws Exception {
String expr = "((A+B)+(C+D))";
assertTrue(target.isBalanced(expr));
}
@Test
public void test4() throws Exception {
String expr = "((A+B)+[C+D]}";
assertFalse(target.isBalanced(expr));
}
@Test
public void test5() throws Exception {
String expr = "A+ {(A+B)+[C+D]}";
assertTrue(target.isBalanced(expr));
}
}