例题1: 720. 词典中最长的单词
class Solution {
public String longestWord(String[] words) {
Arrays.sort(words, (a, b) -> {
if (a.length() != b.length()) {
return a.length() - b.length();
}
// 相同长度下把字典序较大的排在前面
return b.compareTo(a);
});
String ans = "";
Set<String> set = new HashSet<>();
set.add("");
for (String word : words) {
if (set.contains(word.substring(0, word.length() - 1))) {
ans = word;
// 注意是逐步多一,所以,这个添加要放在if里面
set.add(word);
}
}
return ans;
}
}