首页 > 代码库 > 字典树模板

字典树模板

#include<iostream>
#include<string>

using namespace std;

//表示next数组的长度,表示26个字母。如果字符串中有其他字符的话,应相应调整。
//如果所有的字符串都是手机号的话,那就是10了
const int MAX_NUM = 26;
struct trieNode{
    int i;//按需使用,本例子中表示从头到本字符组成的前缀出现的次数
    struct trieNode *next[MAX_NUM];
};

trieNode* CreateTrieNode(){
    trieNode *p = new trieNode;
    p->i = 1;
    for(int i = 0; i < MAX_NUM; i++)
        p->next[i] = NULL;
    return p;
}
void DelTrieTree(trieNode *p)
{
    for(int i=0;i < MAX_NUM; i++)
    {
        if(p->next[i] != NULL)
            DelTrieTree(p->next[i]);
    }
    delete p;
}
void InsertTrieTree(trieNode **root, string str){
    trieNode *p;
    if(*root == NULL){
        p = CreateTrieNode();
        *root = p;
    }
    else
        p = *root;
    int len = str.length();
    int k;
    for(int i = 0; i < len; i++){
        k = str.at(i) - a;
        if(p->next[k] != NULL)
            p->next[k]->i += 1;
        else
            p->next[k] = CreateTrieNode();
        p = p->next[k];
    }
}

int SearchTrieTree(trieNode **root, string str){
    trieNode *p;
    if(*root == NULL)
        return 0;
    p = *root;
    int k, len = str.length();
    for(int i = 0; i < len; i++){
        k = str.at(i) - a;
        if(p->next[k] == NULL)
            return 0;
        p = p->next[k];
    }
    return p->i;
}

int main(){
    trieNode *root = NULL;
    InsertTrieTree(&root, "checking");
    InsertTrieTree(&root, "check");
    InsertTrieTree(&root, "for");
    InsertTrieTree(&root, "checking");
    InsertTrieTree(&root, "program");
    InsertTrieTree(&root, "programmer");
    InsertTrieTree(&root, "cheprogrammer");
    cout << SearchTrieTree(&root, "che") << endl;//输出3
    cout << SearchTrieTree(&root, "prog") << endl;//输出2
}

 

字典树模板