HDOJ 2072 单词数(trie树入门)

本文介绍了一种使用字典树(Trie)来高效处理字符串集合的方法,特别是对于单词计数问题的解决。通过C++代码示例展示了如何构建字典树,并实现了插入单词的功能,最终统计出不重复单词的数量。

思路:

虽然用 set 一下子就做出来了,但还是坚持用字典树实现了一遍。

 

#include <iostream>
using namespace std;

struct node {
    bool isword;
    int child[26];
} trie[10010] ;

int size = 0;
int count = 0;

void Insert(char* word, int i, int rt)
{
    if (!word[i])
    {
        if (!trie[rt].isword)
            ++count, trie[rt].isword = true;
        return ;
    }

    int m = word[i] - 'a';
    if (trie[rt].child[m])
    {
        Insert(word, i + 1, trie[rt].child[m]);
    }
    else
    {
        trie[rt].child[m] = ++size;
        Insert(word, i + 1, size);
    }
}

int main()
{
    char str[2000];
    while (gets(str) && str[0] != '#')
    {
        count = 0;
        size = 0;
        memset(trie, 0, sizeof(trie));

        char word[100];
        int j = 0;
        memset(word, 0, sizeof(word));
        for (int i = 0; str[i] != '\0'; ++i)
        {
            if (str[i] != ' ')
                word[j++] = str[i];
            else if (j)
            {
                Insert(word, 0, 0);
                memset(word, 0, sizeof(word));
                j = 0;
            }
        }
        if (j)
            Insert(word, 0, 0);

        printf("%d\n", count);
    }
    return 0;
}

转载于:https://www.cnblogs.com/kedebug/archive/2013/01/23/2873698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值