class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Tire tire = new Tire();
for (String product : products) {
tire.insert(product);
}
return tire.search(searchWord);
}
class Tire{
Node root;
public Tire(){
root = new Node();
}
public void insert(String word){
Node cur = root;
for (int i = 0; i < word.length(); i++){
int u = word.charAt(i) - 'a';
if (cur.children[u] == null){
cur.children[u] = new Node();
}
cur = cur.children[u];
cur.addWord(word);
}
cur.flag = true;
}
public List<List<String>> search(String word){
List<List<String>> res = new ArrayList<>();
Node cur = root;
for (int i = 0; i < word.length(); i++){
List<String> list = new ArrayList<>();
int u = word.charAt(i) - 'a';
if (cur != null){
cur = cur.children[u];
list = cur == null ? new ArrayList<>() : new ArrayList<>(cur.treeSet);
}
res.add(list);
}
return res;
}
}
class Node{
boolean flag;
Node[] children;
TreeSet<String> treeSet;
public Node(){
flag = false;
children = new Node[26];
treeSet = new TreeSet<>();
}
public void addWord(String word){
treeSet.add(word);
if (treeSet.size() > 3){
treeSet.pollLast();
}
}
}
}
力扣:1268. 搜索推荐系统
最新推荐文章于 2024-06-12 21:00:25 发布
该博客介绍了一个使用 Trie 数据结构来实现产品搜索优化的解决方案。Trie 类包含 insert 方法用于插入产品名,search 方法用于根据输入的搜索词返回相关产品列表。每个节点维护一个子节点数组和一个 TreeSet,用于存储以该节点为前缀的完整单词,并限制存储的单词数量不超过3个。这种方法提高了搜索效率并限制了返回结果的数量。

911

被折叠的 条评论
为什么被折叠?



