fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. final class BalancedParanthesis {
  8.  
  9. private static final Map<Character, Character> brackets = new HashMap<Character, Character>();
  10. static {
  11. brackets.put('[', ']');
  12. brackets.put('{', '}');
  13. brackets.put('(', ')');
  14. }
  15.  
  16. private BalancedParanthesis() {};
  17.  
  18. /**
  19.   * Returns true is parenthesis match open and close.
  20.   * Understands [], {}, () as the brackets
  21.   * It is clients responsibility to include only valid paranthesis as input.
  22.   * A false could indicate that either parenthesis did not match or input including chars other than valid paranthesis
  23.   *
  24.   * @param str the input brackets
  25.   * @return true if paranthesis match.
  26.   */
  27. public static boolean isBalanced(String str) {
  28. if (str.length() == 0) {
  29. throw new IllegalArgumentException("String length should be greater than 0");
  30. }
  31. // odd number would always result in false
  32. if ((str.length() % 2) != 0) {
  33. return false;
  34. }
  35.  
  36. final Stack<Character> stack = new Stack<Character>();
  37. for (int i = 0; i < str.length(); i++) {
  38. if (brackets.containsKey(str.charAt(i))) {
  39. stack.push(str.charAt(i));
  40. } else if (stack.empty() || (str.charAt(i) != brackets.get(stack.pop()))) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. System.out.println(isBalanced("[["));
  49. }
  50. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
true