fork(7) download
  1. import java.util.*;
  2. import java.util.stream.*;
  3. import java.util.function.*;
  4. class Ideone {
  5. public static void main (String[] args) {
  6. String[] input = "chat, ever, snapchat, snap, salesperson, per, person, sales, son, whatsoever, what, so".split(", ");
  7. System.out.println(Arrays.toString(find(input)));
  8. }
  9.  
  10. private static String[] find(String[] array) {
  11. Set<String> words = new LinkedHashSet<>(Arrays.asList(array));
  12. Set<String> otherWords = new HashSet<>(words);
  13. for (Iterator<String> i = words.iterator(); i.hasNext(); ) {
  14. String next = i.next();
  15. otherWords.remove(next);
  16. if (isCompound(next, otherWords)) {
  17. i.remove();
  18. } else {
  19. otherWords.add(next);
  20. }
  21. }
  22. return words.stream().toArray(String[]::new);
  23. }
  24.  
  25. private static boolean isCompound(String string, Set<String> otherWords) {
  26. if (otherWords.contains(string)) {
  27. return true;
  28. }
  29. for (String word : otherWords) {
  30. if (string.startsWith(word)) {
  31. return isCompound(string.replaceAll("^" + word, ""), otherWords);
  32. }
  33. if (string.endsWith(word)) {
  34. return isCompound(string.replaceAll(word + "$", ""), otherWords);
  35. }
  36. }
  37. return false;
  38. }
  39. }
Success #stdin #stdout 0.1s 711680KB
stdin
Standard input is empty
stdout
[chat, ever, snap, per, sales, son, what, so]