642. Design Search Autocomplete System

642. Design Search Autocomplete System


Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character ‘#’). For each character they type except ‘#’, you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:

The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
If less than 3 hot sentences exist, then just return as many as you can.
When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
Your job is to implement the following functions:

The constructor function:

AutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical data. Sentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data.

Now, the user wants to input a new sentence. The following function will provide the next character the user types:

List input(char c): The input c is the next character typed by the user. The character will only be lower-case letters (‘a’ to ‘z’), blank space (’ ‘) or a special character (’#’). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.

Example:
Operation: AutocompleteSystem([“i love you”, “island”,“ironman”, “i love leetcode”], [5,3,2,2])
The system have already tracked down the following sentences and their corresponding times:
“i love you” : 5 times
“island” : 3 times
“ironman” : 2 times
“i love leetcode” : 2 times
Now, the user begins another search:

Operation: input(‘i’)
Output: [“i love you”, “island”,“i love leetcode”]
Explanation:
There are four sentences that have prefix “i”. Among them, “ironman” and “i love leetcode” have same hot degree. Since ’ ’ has ASCII code 32 and ‘r’ has ASCII code 114, “i love leetcode” should be in front of “ironman”. Also we only need to output top 3 hot sentences, so “ironman” will be ignored.

Operation: input(’ ')
Output: [“i love you”,“i love leetcode”]
Explanation:
There are only two sentences that have prefix "i ".

Operation: input(‘a’)
Output: []
Explanation:
There are no sentences that have prefix “i a”.

Operation: input(’#’)
Output: []
Explanation:
The user finished the input, the sentence “i a” should be saved as a historical sentence in system. And the following input will be counted as a new search.

Note:

The input sentence will always start with a letter and end with ‘#’, and only one blank space will exist between two words.
The number of complete sentences that to be searched won’t exceed 100. The length of each sentence including those in the historical data won’t exceed 100.
Please use double-quote instead of single-quote when you write test cases even for a character input.
Please remember to RESET your class variables declared in class AutocompleteSystem, as static/class variables are persisted across multiple test cases. Please see here for more details.

方法1: Trie

discussion:https://leetcode.com/problems/design-search-autocomplete-system/discuss/163292/C%2B%2B-Trie-and-Priority-Queue-(w-destructor)
思路:

主要用到以下这几个结构/函数:

  1. struct TireNode : 和普通的TrieNode 一样, 但是由于这里查找的对象由单词变成了句子,可以出现任意字符,就不能用char[26] children了,需要一个hashmap来查找。但原理不变,是通过这一此查找找到下一个字符的地址, 因此是unordered_map<char, TrieNode*>。除此以外,因为对于每一个TrieNode,它应该能迅速返回以它为结尾,频数最高的句子。那么就需要另一个hashmap来记录<string, int> 也就是句子的频次。
  2. struct cmp: 用来辅助priority_queue排序。排序的对象是谁?那些以同一TrieNode字符为结尾,按频次排序的句子。如果频次相同,还要按字母序二级排序。那么cmp所要比较的就是一个个pair<\string, int>。 注意struct cmp的写法。
  3. TrieNode* root:和普通Trie一样,用来起始整个字典数。
  4. string prefix: 需要这样一个global variable来持续记录之前输入的input
  5. void insert(string & sen, int num): 字典数中的插入操作。这里不同的是,在沿途遇到的每一个节点,都要把这个pair<string, num>加到他们的count map里面。因为下次访问到这个节点,需要能够捞出所有它的子节点中的高频词。
  6. vector< string> search(string & prefix): 对于一个prefix,要返回它可能对应的top k个句子。那么在这个函数里就要建一个priority_queue,来sort当前count map里的所有句子。最后pop k次来返回result,注意pop之前要查空。
  7. AutocompleteSystem(vector<\string> sentences, vector times) : constructor, 注意完成initialize global variables的工作。
  8. vector input(char c):每次输入一个character,先判断是否是“#”以决定是insert还是search。如果是search将当前c加入prefix后调用search。

易错点

class AutocompleteSystem {
private:
    struct TrieNode {
        char c;
        bool isWord;
        unordered_map<char, TrieNode*> children;
        unordered_map<string, int> count;
        TrieNode (char c): c(c), isWord(false) {}
    };
    
    TrieNode* root;
    string prefix; // want this sustain accross inputs
    
    struct cmp {
        bool operator () (const pair<string, int> & a, const pair<string, int> & b){
            if (a.second == b.second){
                return a.first > b.first;
            }
            return a.second < b.second;
        } 
    };
    
    void insert(string sen, int num){
        TrieNode* cur = root;
        for (char c: sen){
            if (cur->children[c] == nullptr){
                cur->children[c] = new TrieNode(c);
            }
            cur = cur -> children[c];
            cur -> count[sen] +=  num;
        }
        cur -> isWord = true;
    }
    
    vector<string> search(string & prefix){
        TrieNode* cur = root;
        for (char c: prefix){
            if (cur -> children[c] == nullptr) return{};
            cur = cur -> children[c];
        }
        
        vector<string> result;
        priority_queue<pair<string, int>, vector<pair<string, int>>, cmp> pq;
    
        for (auto & it: cur -> count){
            pq.push(it);
        }
        
        int k = 3;
        while (!pq.empty() && k-- > 0){
            result.push_back(pq.top().first);
            pq.pop();
        }
        return result;
    }
    
public:
    AutocompleteSystem(vector<string> sentences, vector<int> times) {
        root = new TrieNode(' ');
        prefix = "";
        for (int i = 0; i < sentences.size(); i++){
            insert(sentences[i], times[i]);
        }
    }
    
    vector<string> input(char c) {
        vector<string> result;
        if (c == '#'){
            insert(prefix, 1);
            prefix = "";
            return {};
        }
        else {
            prefix += c;
            result = search(prefix);
        }
        
        return result;
    }
};

/**
 * Your AutocompleteSystem object will be instantiated and called as such:
 * AutocompleteSystem obj = new AutocompleteSystem(sentences, times);
 * vector<string> param_1 = obj.input(c);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值