字典树模板

const int N=27;

struct node{
    int cnt;
    node* childs[N];
    node(){
        cnt=0;
        for(int i=0;i<N;i++)
            childs[i]=NULL;
    }
};

node *root=new node();
node *current,*newnode;

void insert(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-'a';
        if(current->childs[m]!=NULL){
            current=current->childs[m];
            ++(current->cnt);
        }else{
            newnode=new node;
            ++(newnode->cnt);
            current->childs[m]=newnode;
            current=newnode;
        }
    }
}

int search(char *str){
    current=root;
    for(int i=0;i<strlen(str);i++){
        int m=str[i]-'a';
        if(current->childs[m]==NULL)
            return 0;
        current=current->childs[m];
    }
    return current->cnt;
}

 

posted on 2017-04-01 09:07  mkfoy  阅读(153)  评论(0编辑  收藏  举报

导航