搜索推荐系统

题目链接

搜索推荐系统

题目描述


注意点

  • 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<>();
    }
}

关键点

  • 字典树的思想及构建
  • 如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个
  • 如果某段前缀在产品中不存在,则也需要返回一个空的集合,并且该段前缀不存在后面加上其他字母在产品中肯定也不存在
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值