Title:Longest Word in Dictionary 720
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/longest-word-in-dictionary/
1. 见代码注释
时间复杂度:O(n),一次一层循环,用到了Arrays.sort(),时间复杂度应该是nlogn。
空间复杂度:O(n),申请Set。
/**
* 先排序,然后一次判断
* @param words
* @return
*/
public static String longestWord(String[] words) {
Arrays.sort(words);
Set<String> set = new HashSet<>();
String res = "";
for (String word: words) {
if (word.length() == 1 || set.contains(word.substring(0, word.length() - 1))) {
res = word.length() > res.length() ? word : res;
set.add(word);
}
}
return res;
}