字典树模板 HDU - 1251

题意:
给一些单词,换行键后,查找以后输入的单词作为前缀的话们在之前出现过几次。
思路:
字典树模板----像查字典的顺序一样

#include<string>
#include<stdio.h>
#include<iostream>
using namespace std;
struct tire_node
{
    int count;//前缀出现的次数
    tire_node* next[27];//指针数组,装指针
    bool exit;//是否构成单词
    tire_node():count(0),exit(false){//清空,置NULL
        for(int i=0;i<=26;i++)
            next[i]=NULL;
    }
};
void tire_insert(tire_node* root,string &word)//传入字典树根节点 ,单词
{
    tire_node* node=root;//定义结构体指针
    int len=word.size(),id,i=0;
    while(i<len)//遍历单词
    {
        id=word[i]-'a';
        if(node->next[id]==NULL)//如果子节点上没有出现过该字母
            node->next[id]=new tire_node();//指向新的结构体指针
        node=node->next[id];//将下一个子节点作为父亲节点
        i++;//下一个字母
        node->count+=1;//统计以这段字符串为前缀的单词
    }
    node->exit=true;//标记单词
}
int tire_search(tire_node *root,string &word)
{
    tire_node* node=root;
    int id,len=word.size(),i=0;
    while(i<len)
    {
        id=word[i]-'a';
        if(node->next[id]!=NULL)
            node=node->next[id];
        else
            return 0;//该单词没有出现
        i++;
    }
    return node->count;
}
int main()
{
    int flag=0;
    tire_node* root=new tire_node();
    string s;
    while(getline(cin , s))//输入字符串
    {
        if(s.empty())
        {
            flag=1;
            continue;
        }
        if(!flag)
            tire_insert(root,s);
        else
           // printf("%d\n",tire_search(root,s));运行不成功
            cout<<tire_search(root,s)<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值