-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathBalancedDelimiters.java
More file actions
49 lines (35 loc) · 1.24 KB
/
BalancedDelimiters.java
File metadata and controls
49 lines (35 loc) · 1.24 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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class BalancedDelimiters {
private Map<String, String> closeToOpen = new HashMap<>();
public BalancedDelimiters() {
closeToOpen.put(")", "(");
closeToOpen.put("]", "[");
closeToOpen.put("}", "{");
}
public boolean isBalanced(String value) {
Stack<String> openValues = new Stack<>();
for (char ch : value.toCharArray()) {
if (isOpen(ch)) {
openValues.push(String.valueOf(ch));
} else if (isClose(ch)) {
String expectedOpenValue = getOpenValue(ch);
if (isNotMatched(openValues, expectedOpenValue)) return false;
}
}
return openValues.isEmpty();
}
private boolean isNotMatched(Stack<String> openValues, String expectedOpenValue) {
return !openValues.pop().equals(expectedOpenValue);
}
private String getOpenValue(char ch) {
return closeToOpen.get(String.valueOf(ch));
}
private boolean isOpen(char ch) {
return closeToOpen.containsValue(String.valueOf(ch));
}
private boolean isClose(char ch) {
return closeToOpen.containsKey(String.valueOf(ch));
}
}