Hat‘s Words(字典树)

Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 307 Accepted Submission(s): 141

Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.

Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.

Output
Your output should contain all the hat’s words, one per line, in alphabetical order.

Sample Input

a
ahat
hat
hatword
hziee
word

Sample Output

ahat
hatword

题目要求就是根据输入的单词中来判断这个单词是不是由其他两个单词所构成的 (一开始我以为这是判断这个丹墀是不是有hat和另外一个单词构成 后来一提交就是WA 看了别人的解题思路以后感觉心好痛 然后就用字典树来做了)

字典树:
首先需要建树
建完树以后就逐层的去找 如果要查找的元素的第一个元素和根节点的元素的值不一样 那吗这个单词肯定不在这个字典树 如果相等就一层层的向下进行比较 直至比较完成

#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<stdio.h>
#include<stack>
#include<stdlib.h>
#include<vector>

using namespace std;

typedef struct node
{
    int isword ;
    struct node *next[27];
}node;

void Insert(node *root,string str)
{
    node *p = root;
    node *q;
    for(int i =0;i<str.size();i++)
    {
        int id = str[i] -'a';
        if(p->next[id]==NULL)//如果这个节点不存在只需要将其存下来就行了
        {
            node *q = (node *)malloc(sizeof(node));
            q->isword = 0;//初始化
            memset(q->next,0,sizeof(q->next));//指针初始化为NULL
            p->next[id] = q;
        }
      p =p->next[id];//如果这个节点之前已经存在怎只需要移动到下一次层
    }
    p->isword =1;//单词结束的标志
}
int serach(node *r,string str)
{
    node *p = r;
    for(int i =0;i<str.size();i++)
    {
        int id = str[i] -'a';
        if(p->next[id]==NULL)//如果所查找的元素不在这一层里面 则不需要继续查了 呢吗下面也会没有的
            return 0;
        p = p->next[id];//否则就逐层往下面去找
    }
    return p->isword;//最终返回是不是单词
}
void del(node *root)//这一步是动态删除节点 防止内存不够的情况
{
    for(int i =0;i<27;i++)
        if(root->next[i]!=NULL)
            free(root->next[i]);
    free(root);
}
int main()
{
    vector<string> pq;
    string str;
    node *r = (node *)malloc(sizeof(node));
    r->isword = 0;
    memset(r->next,0,sizeof(r->next));
    while(cin>>str)
    {
        pq.push_back(str);
        Insert(r,str);
    }
    for(int i =0;i<pq.size();i++)
    {
        string str = pq[i];
        int len = str.size();
        for(int j =1;j<=len-1;j++)
        {
            string tmp = str.substr(0,j);
            //cout<<tmp<<" ";
            string tmp2 = str.substr(j);
           // cout<<tmp2<<endl;
            if(serach(r,tmp)&&serach(r,tmp2)){
                cout<<str<<endl;
                break;
            }
        }
    }
    del(r);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值