字典树的总结

(1)

字典树,又称单词查找树,Trie树,是一种树形结构,哈希表的一个变种。用于统计,排序和保存大量的字符串(也可以保存其
的)。
优点就是利用公共的前缀来节约存储空间。在这举个简单的例子:比如说我们想储存3个单词,nyist、nyistacm、nyisttc。如果只是
单纯的按照以前的字符数组存储的思路来存储的话,那么我们需要定义三个字符串数组。但是如果我们用字典树的话,只需要定义
一个树就可以了。在这里我们就可以看到字典树的优势了。

(2)字典树的模板(HDU 2072)

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;


#define N 10000010


char s[N];
char word[N];
int cnt;
typedef struct node
{
    int flg;
    struct node *child[26];
} trie;


trie* init_trie()
{
    trie *root;
    root = (trie *)malloc(sizeof(trie));
    root->flg = 0;
    for(int i = 0; i < 26; i++)
        root->child[i] = NULL;
    return root;
}


void insert_trie(trie *root, char *s)
{
    trie *r = root;
    char *p = s;
    while(*p)
    {
        if(r->child[*p - 'a'] == NULL)
            r->child[*p - 'a'] = init_trie();
        r = r->child[*p - 'a'];
        p++;
    }
    r->flg = 1;
}


int search_trie(trie *root, char *s)
{
    trie *r = root;
    char *p = s;
    while(*p && r)
    {
        r = r->child[*p - 'a'];
        p++;
    }
    if(r && r->flg)
        return 0;
    else
    {
        cnt++;
        insert_trie(root, s);
        return 1;
    }
}


int main()
{
    while(gets(s), strcmp(s, "#") != 0)
    {
        cnt = 0;
        int len = strlen(s);
        trie *root = init_trie();
        for(int i = 0; i < len; i++)
        {
            if(s[i] >= 'a' && s[i] <= 'z')
            {
                int k = 0;
                while(s[i] >= 'a' && s[i] <= 'z')
                {
                    word[k++] = s[i];
                    i++;
                }
                word[k] = '\0';
                i--;
                search_trie(root, word);
            }
        }
        memset(s, 0, sizeof(s));
        printf("%d\n", cnt);
    }
    return 0;

}

(3)需要注意的事项

  首先是在判断一个单词是否存在时 ,不仅仅是看所有的字母是否匹配,还要看最后一个匹配的字母是否可以作为一个单词的结尾,然后就是要是想要看某个前缀出现了多少次,用一个变量来记录一下。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值