720 Longest Word in Dictionary

1. Question

Given a list of stringswordsrepresenting an English Dictionary, find the longest word inwordsthat can be built one character at a time by other words inwords. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
If there is no answer, return the empty string.
Example 1:
1
Input: words = ["w","wo","wor","worl", "world"]
2
3
Output: "world"
4
5
Explanation:
6
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Copied!
Example 2:
1
Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
2
3
Output: "apple"
4
5
Explanation:
6
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Copied!
Note:
All the strings in the input will only contain lowercase letters.
The length ofwordswill be in the range[1, 1000].
The length ofwords[i]will be in the range[1, 30].

2. Implementation

(1) Sorting + Trie
1
class Solution {
2
class TrieNode {
3
char val;
4
boolean isWord;
5
TrieNode[] childNode;
6
7
public TrieNode(char val) {
8
this.val = val;
9
childNode = new TrieNode[256];
10
}
11
}
12
public String longestWord(String[] words) {
13
if (words == null || words.length == 0) {
14
return "";
15
}
16
17
Arrays.sort(words);
18
String res = "";
19
20
TrieNode root = new TrieNode(' ');
21
22
for (String word : words) {
23
TrieNode curNode = root;
24
for (int i = 0; i < word.length(); i++) {
25
char c = word.charAt(i);
26
if (curNode.childNode[c] == null && i < word.length() - 1) {
27
break;
28
}
29
else if (curNode.childNode[c] == null) {
30
curNode.childNode[c] = new TrieNode(c);
31
}
32
curNode = curNode.childNode[c];
33
if (i == word.length() - 1) {
34
res = res.length() < word.length()? word : res;
35
}
36
}
37
}
38
return res;
39
}
40
}
Copied!
(2) Sorting + Hash Set
1
class Solution {
2
public String longestWord(String[] words) {
3
if (words == null || words.length == 0) {
4
return "";
5
}
6
7
String res = "";
8
9
Arrays.sort(words);
10
Set<String> set = new HashSet<>();
11
12
for (String word : words) {
13
if (word.length() == 1 || set.contains(word.substring(0, word.length() - 1))) {
14
if (word.length() > res.length()) {
15
res = word;
16
}
17
set.add(word);
18
}
19
}
20
return res;
21
}
22
}
Copied!

3. Time & Space Complexity

Sorting + Trie: 时间复杂度O(nlogn + nL), n是word的个数,L是word的平均长度, 空间复杂度O(nL)
Sorting + Hash Set: 时间复杂度O(nlogn), 空间复杂度O(n)