Closed congr closed 5 years ago
class Solution {
public String longestWord(String[] words) {
Arrays.sort(words);
Set<String> set = new HashSet();
String longest = "";
for (String w : words) {
String p = w.substring(0, w.length()-1);
if (w.length() == 1 || set.contains(p)) {
set.add(w);
if (longest.length() < w.length()) longest = w;
}
}
return longest;
}
}
https://leetcode.com/problems/longest-word-in-dictionary/