- 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 (36 loc) · 1.31 KB
/
Copy pathsolution.java
File metadata and controls
39 lines (36 loc) · 1.31 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
importjava.util.Scanner;
importjava.util.HashMap;
importjava.util.ArrayDeque;
classSolution{
publicstaticvoidmain(String []argh)
{
/* Creating HashMap to match opening brackets(keys) with corresponding closing brackets(values) */
HashMap<Character, Character> map = newHashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
/* Test each expression for validity */
Scannersc = newScanner(System.in);
while(sc.hasNext()) {
Stringexpression = sc.next();
System.out.println(isBalanced(expression, map) ? "true" : "false");
}
sc.close();
}
privatestaticbooleanisBalanced(Stringexpression, HashMap<Character, Character> map) {
if((expression.length() % 2) != 0) {
returnfalse; // odd length strings are not balanced e.g. {}(
}
ArrayDeque<Character> deque = newArrayDeque<>(); // using 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();
}
}