- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
Latest commit
39 lines (32 loc) · 1.22 KB
/
Copy pathSolution.java
File metadata and controls
39 lines (32 loc) · 1.22 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
importjava.util.*;
classSolution{
publicstaticvoidmain(String[] args) {
/* Create HashMap to match opening brackets with closing brackets */
HashMap<Character, Character> map = newHashMap();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
/* Test each expression for validity */
Scannerscan = newScanner(System.in);
while (scan.hasNext()) {
Stringexpression = scan.next();
System.out.println(isBalanced(expression, map) ? "true" : "false" );
}
scan.close();
}
privatestaticbooleanisBalanced(Stringexpression, HashMap<Character, Character> map) {
if ((expression.length() % 2) != 0) {
returnfalse; // odd length Strings are not balanced
}
ArrayDeque<Character> deque = newArrayDeque(); // use deque as a stack
for (inti = 0; i < expression.length(); i++) {
Characterch = expression.charAt(i);
if (map.containsKey(ch)) {
deque.push(ch);
} elseif (deque.isEmpty() || ch != map.get(deque.pop())) {
returnfalse;
}
}
returndeque.isEmpty();
}
}