词典中最长的单词(720-java)
public class LC242_720_longestWord {
public static String longestWord(String[] words) {
Set<String> set = new HashSet<>();
for (String word : words) {
set.add(word);
}
Arrays.sort(words, (a, b) -> a.length() == b.length()
? a.compareTo(b) : b.length() - a.length());
for (String word : words) {
boolean flag = true;
for (int i = 1; i < word.length(); i++) {
if (!set.contains(word.substring(0, i))) {
flag = false;
break;
}
}
if (flag) {
return word;
}
}
return "";
}
public static void main(String[] args) {
System.out.println(longestWord(new String[]{"w", "wo", "wor", "worl", "world"}));
}
}