2017-02-18 23:43:07 -06:00
|
|
|
// Author: Rodney Shaghoulian
|
2018-07-27 16:45:56 -07:00
|
|
|
// Github: github.com/RodneyShag
|
|
|
|
|
// HackerRank: hackerrank.com/RodneyShag
|
2017-02-18 23:43:07 -06:00
|
|
|
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
import java.util.HashMap;
|
2017-04-05 18:42:35 -05:00
|
|
|
import java.util.ArrayDeque;
|
|
|
|
|
|
|
|
|
|
// ArrayDeque is "likely to be faster than Stack when used as a stack" - Java documentation
|
2017-02-18 23:43:07 -06:00
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-05 18:42:35 -05:00
|
|
|
private static boolean isBalanced(String expression, HashMap<Character, Character> map) {
|
2017-02-18 23:43:07 -06:00
|
|
|
if ((expression.length() % 2) != 0) {
|
2017-04-05 18:42:35 -05:00
|
|
|
return false; // odd length Strings are not balanced
|
|
|
|
|
}
|
|
|
|
|
ArrayDeque<Character> deque = new ArrayDeque<>(); // use deque as a stack
|
2017-02-18 23:43:07 -06:00
|
|
|
for (int i = 0; i < expression.length(); i++) {
|
|
|
|
|
Character ch = expression.charAt(i);
|
|
|
|
|
if (map.containsKey(ch)) {
|
2017-04-05 18:42:35 -05:00
|
|
|
deque.push(ch);
|
|
|
|
|
} else if (deque.isEmpty() || ch != map.get(deque.pop())) {
|
2017-02-18 23:43:07 -06:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-04-05 18:42:35 -05:00
|
|
|
return deque.isEmpty();
|
2017-02-18 23:43:07 -06:00
|
|
|
}
|
|
|
|
|
}
|