fork download
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class Main
  5. {
  6. public static void main(String[] args)
  7. {
  8. String mainstr = "[[data link control], [communication, []], [computer, [applications of computer, number of computer]], [world wide web], [lesson, [covered in lesson]], [access to remote], [marketing and sale], [electronic fund transfer], [network, [network of network, wide area network, communication network, computer network, [area network, [local area network, metropolitan area network]]]]]";
  9. String search = "area network";
  10. Pattern p = Pattern.compile("(?:^|, |\\[)(" + search + ")(?:]|, |$)");
  11. Matcher m = p.matcher(mainstr);
  12. if (m.find())
  13. {
  14. int start = m.start(1);
  15. int end = start + search.length();
  16. int count = 0;
  17. int pos = end;
  18. if (mainstr.charAt(end+2) == '[')
  19. {
  20. while (count != -1)
  21. if (mainstr.charAt(++pos) == ']')
  22. count--;
  23. else if (mainstr.charAt(++pos) == '[')
  24. count++;
  25. System.out.println("Ancestors = " + mainstr.substring(end+2, pos-1));
  26. }
  27. count = 0;
  28. pos = start;
  29. int lastComma = -1;
  30. while (count != 2)
  31. switch (mainstr.charAt(--pos))
  32. {
  33. case ']': count--; break;
  34. case '[': count++; break;
  35. case ',': lastComma = pos;
  36. }
  37. System.out.println("Parent = " + mainstr.substring(pos+1, lastComma));
  38. }
  39. }
  40. }
  41.  
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
Ancestors = [local area network, metropolitan area network]
Parent = network of network