-
Notifications
You must be signed in to change notification settings - Fork 22
/
soln.java
35 lines (32 loc) · 1.22 KB
/
soln.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
import java.util.*;
class Solution{
public static void main(String[] args) {
/* Create HashMap to match opening brackets with closing brackets */
HashMap<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
/* Test each expression for validity */
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String expression = scan.next();
System.out.println(isBalanced(expression, map) ? "true" : "false" );
}
scan.close();
}
private static boolean isBalanced(String expression, HashMap<Character, Character> map) {
if ((expression.length() % 2) != 0) {
return false; // odd length Strings are not balanced
}
ArrayDeque<Character> deque = new ArrayDeque<>(); // use deque as a stack
for (int i = 0; i < expression.length(); i++) {
Character ch = expression.charAt(i);
if (map.containsKey(ch)) {
deque.push(ch);
} else if (deque.isEmpty() || ch != map.get(deque.pop())) {
return false;
}
}
return deque.isEmpty();
}
}