Hat’s Words 【字典树 判断字符串是否可以为字符串集中两个字符串组成】

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

思路 : 搜索每一个单词,每一个单词是不是分为两半,分开考虑,依次判定就行;
代码

#include <cstdio>
#include <cstring>
#define MAX 50001
using namespace std;
char str[MAX][101];
int ch[MAX][101];
int word[MAX];//这里 记录单词数目这个数组没用上
int val[MAX];//标记是否为单词节点
int sz, n;
void init(){
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
    memset(word, 0, sizeof(word));
}
int idx(char x)  {return x - 'a';}
void insert(char *s){
    int i, j, l = strlen(s);
    int u = 0;
    for(i = 0; i < l; i++)
    {
        int c = idx(s[i]);
        if(!ch[u][c])
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;//不是单词节点
            ch[u][c] = sz++;
        }
        u = ch[u][c];
        word[u]++;
    }
    val[u] = 1;
}
bool find(char *s)//判断该字符串 是不是 字符串集里面的一个字符串
{
    int i, j, l = strlen(s);
    int u = 0;
    for(i = 0; i < l; i++)
    {
        int c = idx(s[i]);
        if(!ch[u][c]) return false;
        u = ch[u][c];
    }
    return val[u];//最后一个是不是单词节点
}
int judge(char *s)//判断该字符串 能否由另外两个字符串构成
 {
    int i, j, l = strlen(s);
    if(l == 1)  return 0;
    char front[MAX], after[MAX];
    char convert[MAX];
    strcpy(convert, s);
    strrev(convert);
    int k = 0;
    for(i = 0; i < l; i++)
    {
        if(i == l-1)
        break;
        front[k++] = s[i];
        front[k] = '\0';
        convert[l-k] = '\0';
        if(find(front))//前面一部分可以找到
        {
            strcpy(after, convert);
            strrev(after);
            if(find(after))//后面一部分可以找到
            return 1;
        }
    }
    return 0;
}
int main(){
    n = 0;
    init();
    while(scanf("%s", str[n])!= EOF)
        insert(str[n++]);
    for(int i = 0; i < n; i++)
    {
        if(judge(str[i])) //查找成功
        printf("%s\n", str[i]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值