hiho一下第二周#1014 : Trie树

Trie树即为前缀树,通过它可以找到前缀相同的字符串。

class Trie {
private:
    int count;  //用于计数
    Trie *next[26];
public:
    Trie() :count(1) {
        for (unsigned i{ 0 }; i < 26; ++i)  next[i] = NULL;
    }
    void insert(Trie *root, string &s) {
        Trie *p = root;
        for (unsigned i{ 0 }; i < s.size(); ++i) {
            unsigned j = s[i] - 'a';
            if (p->next[j]) {
                ++p->next[j]->count;
            }else{
                Trie *q = new Trie;
                p->next[j] = q;
            }
            p = p->next[j];
        }
    }
    int query(Trie *root, string &s) {
        bool flag = false;
        Trie *p = root;
        for (unsigned i{ 0 }; i < s.size(); ++i) {
            unsigned j = s[i] - 'a';
            if (!p->next[j]) {
                flag = true;
                break;
            }
            p = p->next[j];
        }
        if (flag)   return 0;
        else    return p->count;
    }
};

你可能感兴趣的:(hiho)