fork(2) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Ideone
  6. {
  7. public static void main (String[] args) throws java.lang.Exception
  8. {
  9. String s = "foo bar [first [second] [third]] asdf ]]]] [now [get] me [mor[e]] of this]]";
  10. List<String> balanced = getBalancedSubstrings(s, '[', ']', true);
  11. for (String str: balanced) {
  12. System.out.println(str);
  13. }
  14. }
  15.  
  16. public static List<String> getBalancedSubstrings(String s, Character markStart,
  17. Character markEnd, Boolean includeMarkers)
  18. {
  19. List<String> subTreeList = new ArrayList<String>();
  20. int level = 0;
  21. int lastOpenDelimiter = -1;
  22. for (int i = 0; i < s.length(); i++) {
  23. char c = s.charAt(i);
  24. if (c == markStart) {
  25. level++;
  26. if (level == 1) {
  27. lastOpenDelimiter = (includeMarkers ? i : i + 1);
  28. }
  29. }
  30. else if (c == markEnd) {
  31. if (level == 1) {
  32. subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
  33. }
  34. if (level > 0) level--;
  35. }
  36. }
  37. return subTreeList;
  38. }
  39. }
  40.  
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
[first [second] [third]]
[now [get] me [mor[e]] of this]