Trie(字典树)

前两天看到hihoCoder上一道Trie树的题,正好学习一下新的数据结构和它的应用
题目链接: http://hihocoder.com/problemset/problem/1014
题目简介:输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。
样例输入:
5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab
样例输出:
1
0
3
0
0

自己编写的AC代码如下:

#include<iostream>
#include<vector>
#include<string>
using namespace std;
#define MAX 26
struct Trie
{
    int count;
    Trie*child[MAX];
};

void Create(Trie *tree)
{
    tree->count = 0;
    for (int i = 0; i < MAX;i++)
    {
        tree->child[i] = NULL;
    }
}

void Destroy(Trie *tree)
{
    for (int i = 0; i < MAX; i++)
    {
        if (tree->child[i])
            Destroy(tree->child[i]);
    }
    delete tree;
    tree = NULL;
}

void Insert(Trie *head)
{
    int n; string s;
    Trie *tree = NULL;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> s;
        int len = s.size();
        tree = head;
        for (int j = 0; j < len; j++)
        {
            int index = s[j] - 'a';
            if (tree->child[index])
            {
                tree->child[index]->count++;
                tree = tree->child[index];
            }

            else
            {
                tree->child[index] = new Trie();
                tree = tree->child[index];
                tree->count = 1;
                for (int k = 0; k < MAX; k++)
                {
                    tree->child[k] = NULL;
                }
            }       
        }
    }
    tree = NULL;
}

void Search(Trie *head)
{
    int m; string s;
    Trie *tree = NULL;
    cin >> m;
    for (int i = 0; i < m; i++)
    {
        cin >> s;
        int len = s.size();
        tree = head;
        int j;
        for (j = 0; j < len; j++)
        {
            int index = s[j] - 'a';
            if (tree->child[index])
                tree = tree->child[index];
            else
            {
                cout << 0 << endl;
                break;
            }       
        }
        if (j==len)
            cout << tree->count << endl;
    }
}
int main()
{
    Trie *head = new Trie();
    Create(head);
    Insert(head);
    Search(head);
    Destroy(head);
    return 0;
}

PS:代码中的删除应该有点问题,只是程序中没有体现出来,连最简单的删除节点都忘了,囧,应该定义两个节点,一个前驱,一个当前,删除当前节点,前驱对应的指针置为NULL。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值