I was doing hackerrank and I am trying to understand the solution written by RodneyShag. (Credit: He wrote the solution, not me) I am trying to understand the last part.
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayDeque;
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();
}
}
The explanation (provided by him) is
Our map only has 3 keys: (, [, { The linemap.containsKey(ch) checks if it's one of the above keys, and if so, pushes it to the deque. The next part of
deque.isEmpty() || ch != map.get(deque.pop())
checks if we have a valid expression. Since at this point, we know the character is not (, [, or {, so we must have a valid closing brace. if
1) our deque is empty, and we just read a closing brace, then we have an invalid expression (and return false)
2) if the closing brace does not match the opening brace that we popped off the deque, then we have an invalid expression (and return false)
I understand that
Character ch = expression.charAt(i);
is supposed to : check whether each variable at expression is = to variable in map Character.
Why is it only ([{
in map? Isn't there ( ) [ ] { }
in map?