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. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String s = "some text(text here(possible text)text(possible text(more text)))end text";
  13. List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
  14. System.out.println("Balanced substrings:\n" + balanced);
  15.  
  16. }
  17. public static List<String> getBalancedSubstrings(String s, Character markStart,
  18. Character markEnd, Boolean includeMarkers) {
  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. level--;
  35. }
  36. }
  37. return subTreeList;
  38. }
  39. }
Success #stdin #stdout 0.1s 320576KB
stdin
Standard input is empty
stdout
Balanced substrings:
[(text here(possible text)text(possible text(more text)))]