leetcode208. 实现 Trie (前缀树)

const int N=1e5;
class Trie {
public:
    int son[N][26],cnt[N],idx;
    Trie() {
        idx=0;
        memset(son,0,sizeof son);
        memset(cnt,0,sizeof cnt);
    }
    
    void insert(string word) {
        int p=0;
        for(int i=0;i<word.size();i++){
            int t=word[i]-'a';
            if(!son[p][t])son[p][t]=++idx;
             p=son[p][t];
        }
        cnt[p]++;
    }
    
    bool search(string word) {
        int p=0;
        for(int i=0;i<word.size();i++){
            int t=word[i]-'a';
            if(!son[p][t])return false;
            p=son[p][t];
        }
        return cnt[p];
    }
    
    bool startsWith(string prefix) {
        int p=0;
        for(int i=0;i<prefix.size();i++){
            int t=prefix[i]-'a';
            if(!son[p][t])return false;
            p=son[p][t];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */