fork(1) download
  1. import java.util.*;
  2.  
  3. class Main {
  4.  
  5. public static boolean isBalanced(String str, int i, char expected) {
  6. /* end has reached and not expecting anything then break */
  7. if (i == str.length())
  8. return expected == '\0';
  9.  
  10. char c = str.charAt(i);
  11. /* expecting something and it is a closing type */
  12. /* then it should match expecting type */
  13. if (expected != '\0' && (c == '}' || c == ')' || c == ']'))
  14. return (c == expected);
  15.  
  16. char e = expected;
  17.  
  18. /* is one of opening type, make expected to it corresponding closing type */
  19. if (c == '{' || c == '[' || c == '(')
  20. e = c == '{' ? '}' : (c == '[' ? ']' : ')');
  21.  
  22. /* call recursively with i + 1 */
  23. return isBalanced(str, i + 1, e);
  24.  
  25. }
  26.  
  27. public static void main(String args[]) {
  28. Scanner sc = new Scanner(System.in);
  29. String line;
  30. while (sc.hasNextLine()) {
  31. line = sc.nextLine();
  32. System.out.println(isBalanced(line, 0, '\0'));
  33. }
  34. }
  35. }
Success #stdin #stdout 0.09s 380672KB
stdin
[]]
([]
{{{{}}[()([])]}[[[()]()]()]}
stdout
true
true
true