-
Notifications
You must be signed in to change notification settings - Fork 93
/
ParenthesisBalanced.java
64 lines (56 loc) · 1.9 KB
/
ParenthesisBalanced.java
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
import java.util.HashMap;
public class ParenthesisBalanced {
public static void main(String[] args) {
String str = "[[{{()()}}]]";
System.out.println(isBalanced(str) ? "Balanced" : "Not balanced");
}
private static boolean isBalanced(String str) {
HashMap<Character, Integer> hm = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
char openingBracket = '\0';
switch (ch) {
case ']':
case '[':
openingBracket = '[';
break;
case '}':
case '{':
openingBracket = '{';
break;
case ')':
case '(':
openingBracket = '(';
break;
}
if (openingBracket != '\0') {
Integer count = hm.get(openingBracket);
if (count == null) {
if (ch == ']' || ch == '}' || ch == ')') {
return false;
} else {
hm.put(openingBracket, 1);
}
} else {
switch (ch) {
case ']':
case '}':
case ')':
if (count == 1) {
hm.remove(openingBracket);
} else {
hm.put(openingBracket, count - 1);
}
break;
case '[':
case '{':
case '(':
hm.put(openingBracket, count + 1);
break;
}
}
}
}
return hm.size() == 0;
}
}