Trie树

Trie树也称字典树,由于其效率很高,因此在在字符串查找、前缀匹配等中应用很普遍,其高效率是以空间为代价的。利用串构建一个字典树,这个字典树保存了串的公共前缀信息,所以能够下降查询操做的复杂度。spa

下面以单词为例,插入、查找和删除实现code

#define MaxN 26
typedef struct TrieNode
{
    bool isStr; //标记是否构成单词
    struct TrieNode *next[MaxN];
}Trie;

void InsertWords(Trie *root, const char *s)
{
    if(root == NULL || *s == '\0')
        return;
    Trie *p = root;
    while(*s != '\0')
    {
        if(p->next[*s-'a']==NULL)
        {
            Trie *temp = new Trie();
            for(int i = 0; i< MaxN; i++)
            {
                temp->next[i] = NULL;
            }
            temp->isStr = false;
            p->next[*s-'a'] = temp;
            p = p->next[*s-'a'];
        }
        else
        {
            p = p->next[*s-'a'];
        }
        s++;
    }
    p->isStr = true;
}

int SearchWord(Trie *root, const char *s)
{
    Trie *p = root;
    while(p != NULL && *s != '\0')
    {
        p = p->next[*s-'a'];
        s++;
    }
    return (p != NULL && p->isStr == true);
}

void delTrie(Trie *root)
{
    for(int i = 0; i < MaxN; i++)
    {
        if(root->next[i] != NULL)
            delTrie(root->next[i]);
    }
    delete root;
}
相关文章
相关标签/搜索