Leetcode 1032. Stream of Characters Trie树

题意

  • 一个数据结构题,给定一个字典,初始化一个数据结构。每次查询是给一个字符,返回的信息是一个bool类型的。如果存在一个K,使得从当前字符开始往前看K个构建的字符串落在字典中,则返回true否则false
  • 数据范围:1 <= words.length <= 20001 <= words[i].length <= 2000,查询总数不超过40000

思路

  • 对字典中字符串进行反转,构建一棵字典树
  • 查询中维护一个双端队列,存储前T个字符,T = max words[i].length
  • 每次来一个字符之后,在字典树中检索即可
class StreamChecker {
public:
    vector<unordered_map<char, int>> tree;
    vector<bool> isleaf;
    int max_len;
    deque<int> q;
    void add_word(const string& s){
        int now = 0;
        for (int i = s.length() - 1; i >= 0; i--){
            auto ch = s[i];
            if (tree[now].find(ch) == tree[now].end()){
                tree[now][ch] = tree.size();
                now = tree.size();
                tree.push_back(unordered_map<char, int>());
                isleaf.push_back(false);
            }
            else{
                now = tree[now][ch];
            }
        }
        isleaf[now] = true;
    }
    StreamChecker(vector<string>& words) {
        tree.push_back(unordered_map<char, int>());
        isleaf.push_back(false);
        max_len = 0;
        for (auto& s : words){
            max_len = max(max_len, int(s.length()));
            add_word(s);
        }
    }
    bool query(char letter) {
        q.push_front(letter);
        if (q.size() > max_len)
            q.pop_back();
        int now = 0;
        for (auto it : q){
            if (tree[now].find(it) == tree[now].end())
                return false;
            now = tree[now][it];
            if (isleaf[now]){
                return true;
            }
       }
        return false;
    }

};
/**
 * Your StreamChecker object will be instantiated and called as such:
 * StreamChecker* obj = new StreamChecker(words);
 * bool param_1 = obj->query(letter);
 */

你可能感兴趣的:(ACM-字符串,ACM_Trie树)