1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public String longestWord(String[] words) { Set<String> wordSet = new HashSet<>(Arrays.asList(words)); Arrays.sort(words, (o1, o2) -> { int diff = Integer.compare(o2.length(), o1.length()); if (diff != 0) { return diff; } else { return o1.compareTo(o2); } });
for (String word : words) { if (match(word, wordSet)) { return word; } } return ""; }
private boolean match(String word, Set<String> wordSet) { for (int endIndex = word.length() - 1; endIndex > 0; endIndex--) { if (!wordSet.contains(word.substring(0, endIndex))) { return false; } }
return true; } }
|
References
720. Longest Word in Dictionary