Trie

1.字符串统计

用vector来优化时间和空间,idx为索引

#include <cstdio>
#include <cstring>
#include <vector>
#include <cstdlib>
using namespace std;
const int N = 2e5+5;

int idx;
char cmd[5];
char str[N];
struct TrieNode{
    int cnt;
    int nex[26];
    TrieNode(){
        cnt = 0;
        for(int i = 0; i < 26; i++){
            nex[i] = -1;
        }
    }
};

vector<TrieNode> tree(1); 
// 以某个结点为结尾的字符串出现的总次数为cnt
// vector优化时间(不免不必要的初始化)和空间

void add(int len){
    int rt = 0;
    for(int i = 0; i < len; i++){
        if(tree[rt].nex[str[i]-'a'] == -1){
            tree[rt].nex[str[i]-'a'] = ++idx;
            tree.push_back(TrieNode());
        }
        rt = tree[rt].nex[str[i]-'a'];
    }
    tree[rt].cnt++;
}
int query(int len){
    int rt = 0;
    for(int i = 0; i < len; i++){
        if(tree[rt].nex[str[i]-'a'] == -1){
            return 0;
        }else{
            rt = tree[rt].nex[str[i]-'a'];
        }
    }

    return tree[rt].cnt;
}
int main(){
    int n;
    scanf("%d",&n);
    while(n--){
        scanf("%s%s",cmd,str);
        if(cmd[0]=='I'){
            add(strlen(str));
        }else{
            printf("%d
",query(strlen(str)));
        }
    }
    system("pause");
    return 0;
}
---- suffer now and live the rest of your life as a champion ----
原文地址:https://www.cnblogs.com/popodynasty/p/13962565.html