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. 搜索推荐系统
最新推荐文章于 2022-10-07 13:43:33 发布