(字典树)Hat’s Words -- HDOJ

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

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

Author
戴帽子的

Recommend
Ignatius.L

/*
    根据每个单词建立一棵树
    对每个单词拆成两部分,分别对这两部分去树中查找,
    判断是否这两部分,都在树中,若都在,则说明这个单词
    是由两个单词组成的
*/
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<map>
#include<set>
#include<string>
#define mod 1000000007

using namespace std;

typedef struct Node
{
    bool is;
    Node *nxt[27];//26个英文字母
    Node()
    {
        is = false;//is为true,则代表一个单词的结束
        memset(nxt,0,sizeof(nxt));
    }
}Node;
string word[50005];

void Insert(Node * root,string s)
{

    int indx=0;
    Node *p = root;
    while(indx<s.size())//将单词的每个字母都插入到树中
    {
        int k = s[indx++] - 'a';
        if(p->nxt[k] == 0)//如果k位置不存在,我们就新生成一个节点
            p->nxt[k] = new Node();
        p = p->nxt[k];
    }
    p->is = true;//单词插入结束,做标记
}
bool Search(Node *root,string s)
{
    Node *p = root;
    int indx = 0;
    while(indx < s.size())
    {
        int k = s[indx++] - 'a';
        if(p->nxt[k] == 0)//要查询的第indx个字母不存在,则单词不在这个树中
            return 0;
        p = p->nxt[k];
    }
    if(p->is)//查询完整个单词,正好到达单词结束的标记地方
        return 1;
    return 0;
}
int main(void)
{
 //   freopen("in.txt","r",stdin);
    int indx = 0;
    Node *root = new Node();
    while(cin>>word[indx])
    {
        Insert(root,word[indx++]);
    }
    for(int i=0; i<indx; ++i)
    {
        bool flg = false;
        for(int j=1; j<word[i].size(); ++j)
        {
            //将单词分割成两部分
            string str1 = word[i].substr(0,j);
            string str2 = word[i].substr(j,word[i].size()-j);
            //其中有个为空,则不做操作
            if(!str1.size() || !str2.size())
                continue;
            //两部分都满足在树中
            if(Search(root,str1) && Search(root,str2))
            {
                flg = true;
                break;
            }
        }
        if(flg)
            cout << word[i]<<endl;

    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值