题目链接
搜索推荐系统
题目描述
注意点
- products[i] 中所有的字符都是小写英文字母
- searchWord 中所有字符都是小写英文字母
- 如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个
解答思路
- 可以根据单词中的字母构建字典树,需要注意的是,如果同一条路径中(前缀相同)的单词超过三个,只需要取字典序最小的三个即可。所以先将products按字典序进行排序,然后从前往后将每个产品的字母添加到字典树中
- 需要创建一个字典树的结构,其中childTrie是其当前字母后面的下一个字母(a~z),indexList为此时路径所包含的产品(字典序最小的三个)
代码
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> res = new ArrayList<>();
Arrays.sort(products);
Trie root = new Trie();
for (int i = 0; i < products.length; i++) {
Trie trie = root;
for (char c : products[i].toCharArray()) {
if (trie.childTrie[c - 'a'] == null) {
trie.childTrie[c - 'a'] = new Trie();
}
trie = trie.childTrie[c - 'a'];
if (trie.indexList.size() < 3) {
trie.indexList.add(i);
}
}
}
Trie trie = root;
boolean hasWord = true;
for (char c : searchWord.toCharArray()) {
List<String> sonRes = new ArrayList<>();
if (hasWord && trie.childTrie[c - 'a'] != null) {
trie = trie.childTrie[c - 'a'];
for (int i = 0; i < trie.indexList.size(); i++) {
int idx = trie.indexList.get(i);
sonRes.add(products[idx]);
}
} else {
hasWord = false;
}
res.add(sonRes);
}
return res;
}
}
class Trie {
Trie[] childTrie;
List<Integer> indexList;
Trie() {
childTrie = new Trie[26];
indexList = new ArrayList<>();
}
}
关键点
- 字典树的思想及构建
- 如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个
- 如果某段前缀在产品中不存在,则也需要返回一个空的集合,并且该段前缀不存在后面加上其他字母在产品中肯定也不存在