每日一道leetcode

发布于:2025-05-17 ⋅ 阅读:(21) ⋅ 点赞:(0)

1268. 搜索推荐系统 - 力扣(LeetCode)

题目

给你一个产品数组 products 和一个字符串 searchWord ,products  数组中每个产品都是一个字符串。

请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个。

请你以二维列表的形式,返回在输入 searchWord 每个字母后相应的推荐产品的列表。

示例 1:

输入:products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
输出:[
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
解释:按字典序排序后的产品列表是 ["mobile","moneypot","monitor","mouse","mousepad"]
输入 m 和 mo,由于所有产品的前缀都相同,所以系统返回字典序最小的三个产品 ["mobile","moneypot","monitor"]
输入 mou, mous 和 mouse 后系统都返回 ["mouse","mousepad"]

示例 2:

输入:products = ["havana"], searchWord = "havana"
输出:[["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

示例 3:

输入:products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
输出:[["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

示例 4:

输入:products = ["havana"], searchWord = "tatiana"
输出:[[],[],[],[],[],[],[]]

提示:

  • 1 <= products.length <= 1000
  • 1 <= Σ products[i].length <= 2 * 10^4
  • products[i] 中所有的字符都是小写英文字母。
  • 1 <= searchWord.length <= 1000
  • searchWord 中所有字符都是小写英文字母。

思路

  1. 先构建前缀树。
  2. 然后定义一个寻找前三字典序前缀匹配的函数:
    1. 先查找是否存在此前缀序列,没有直接返回;
    2. 如果有则判断该前缀是否已是单词,是则加入然后更新记录数;
    3. 然后按字典序深度优先搜索剩下的可能,直到达到三个满足条件的或所有字典序都被遍历完成。

代码实现

class TrieNode {
    public:
        bool isWord = false;
        TrieNode* children[26];
};
class Trie {
    public:
        TrieNode* root;
        Trie() {
            root = new TrieNode();
        }
        void insert(string word) {
            int c;
            TrieNode* cur = root;
            for(int i = 0; i < word.length(); ++i) {
                c = int(word[i]-'a');
                if(cur->children[c] == nullptr) cur->children[c] = new TrieNode();
                cur = cur->children[c]; 
            }
            cur->isWord = true;
        }
        int findTop3(string prefix, TrieNode* cur, int cnt, vector<string> &ans, string word) {
            int c;
            for(int i = 0; i < prefix.length(); ++i) {
                c = int(word[i]-'a');
                if(cur->children[c] == nullptr) return 0; 
                cur = cur->children[c];
            }
            if(cur->isWord) {
                cnt++;
                ans.push_back(word);
            }
            if(cnt == 3) return cnt;
            for(int i = 0; i < 26; ++i) {
                if(cur->children[i] != nullptr) {
                    cnt = findTop3("", cur->children[i], cnt, ans, word+char(i+'a'));
                    if(cnt == 3) break;
                }
            }
            return cnt;
        }
};
class Solution {
public:
    vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
        sort(products.begin(), products.end());
        vector<vector<string>> ans;
        vector<string> wordList;
        string sstring = "";
        Trie* tree = new Trie();
        for(int i = 0; i < products.size(); ++i) {
            tree->insert(products[i]);
        } 
        for(int i = 0; i < searchWord.length(); ++i) {
            wordList.clear();
            sstring += searchWord[i];
            tree->findTop3(sstring , tree->root, 0, wordList, sstring);
            ans.push_back(wordList);
        }
        return ans;
    }
};

复杂度分析

  • 时间复杂度:设searchWord长度为n,前缀树的深度为D,那么最坏的时间复杂度为O(n*L*26)。
  • 空间复杂度:设products所有字符串长度为m,则空间复杂度为O(max(m, 3n, D))。

官方题解

  • 惨不忍睹,感觉自己写的逻辑好复杂,实际的时空间复杂度也是高的离谱,还是好好学习吧。

字典树

  • 这里官解很重要的一个地方就是在插入过程中提前利用优先队列做了优化——即在插入过程中,每一层都将该单词插入到节点的单词队列中去,那么在查找到这个前缀的时候直接查询这个优先队列,就知道拥有该前缀的的单词有哪些了。
  • 更进一步,因为只有找三个字典序最小的,所以我们用字典序最大来定义有限队列后,只要保持队列长度为3,那么这三个肯定就是结果——每次插入新的单词后,超过三个直接弹出字典序最大的一个。
  • 那么插入完成后只要遍历到前缀的最后一个节点,就直接查队列即可,否则就是没答案。
  • 复现一下:
class Trie {
    public:
        unordered_map<char, Trie*> children;
        priority_queue<string> words; // 默认是先弹大的(大根堆)
};
class Solution {
public:
    void insert(string word, Trie* root) {
        Trie* cur = root;
        for(int i = 0; i < word.length(); ++i) {
            if(!cur->children.count(word[i])) cur->children[word[i]] = new Trie();
            cur = cur->children[word[i]];
            cur->words.push(word);
            if(cur->words.size() > 3) cur->words.pop();
        }
    }
    vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
        Trie* root = new Trie(), *cur;
        vector<vector<string>> ans;
        for(int i = 0; i < products.size(); ++i) {
            insert(products[i], root);
        }
        cur = root;
        bool invalid = false;
        for(int i = 0; i < searchWord.length(); ++i) {
            if(invalid || !cur->children.count(searchWord[i])) {
                ans.emplace_back();
                invalid = true;
            }
            else {
                cur = cur->children[searchWord[i]];
                vector<string> tmp;
                while(!cur->words.empty()) {
                    tmp.emplace_back(cur->words.top());
                    cur->words.pop(); // 只访问一次所以弹完就算了
                }
                reverse(tmp.begin(), tmp.end());
                ans.emplace_back(std::move(tmp));
            }
        }
        return ans;
    }
};
  • 很好,时空间开销都缩小到了原来的1/5,分析一下复杂度情况:
    • 时间复杂度:设searchWord长度仍然为n,products所有字符串的长度为m,那么内部的出队入队还有反转数组时间开销都是O(1)的,所以总的时间复杂度为O(n+m)。
    • 空间复杂度:O(m)。
  • 这里有一些函数是有优化效果的,如emplace_back和move,似乎他们都是直接进行所有权转移,避免了一次拷贝构造函数。
  • 这里还有一个要注意的点,如果在vector中插入一个空表,如果用push_back的话就要先定义一个空的数据结构,而如果用emplace_back就直接空着函数会自动默认填空表。

二分查找

  • 因为构建字典树需要额外的时间空间,所以还有一种直接在数组中原地查找的思路。
  • 首先我们想要做的是按字典序从小到大记录结果,所以不妨直接将products数组按字典序排列。
  • 接着查找过程中只用使用二分的方法找到字典序大于等于待查前缀的单词的位置,然后依次往后比较三个单词的前缀是否为它(因为这时前缀相同的单词肯定是按字典序连续的)。
class Solution {
public:
    vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
        vector<vector<string>> ans;
        sort(products.begin(), products.end());
        vector<string>::iterator iter_left = products.begin(), iter_find;
        string prefix = "";
        for(int i = 0; i < searchWord.length(); ++i) {
            prefix += searchWord[i];
            iter_find = lower_bound(iter_left, products.end(), prefix); // 满足条件的下界
            vector<string> tmp;
            for(int j = 0; j < 3; ++j) {
                // 条件一:不能超出数组范围;条件二:是前缀而不是其他子串。
                if(iter_find+j < products.end() && (*(iter_find+j)).find(prefix)==0) {
                    tmp.emplace_back(*(iter_find+j));
                }
            }
            ans.emplace_back(move(tmp));
            iter_left = iter_find; // 更新二分端点
        }
        return ans;
    }
};
  • 这个方法其实更多地是利用已经实现的一下优化过的函数的性质来优化效率,感觉如果让我自己写这个二分求下界的方法我也得弄很久。
  • 时间复杂度:对字符串数组排序的时间复杂度为O(m*logN),P为product数组的长度,二分查找的时间复杂度为O(n*logn*logN),所以总的时间复杂度为O((m+n*logn)*logN)。
  • 空间复杂度:根据官解的说法sort函数的空间复杂度是O(logn),不过一般的快排的空间复杂度应该是O(nlogn)的,查了一下好像是优化过的分段快排的思想,可能把空间复杂度降下来了吧。

网站公告

今日签到

点亮在社区的每一天
去签到