题意:如果有个单词是由其它两个单词组成的,就输出。
思路:每个结点加个标志位,判断是不是一个完整的单词。如果进行查找操作,查找成功之后,把查找成功的部分截掉,查找剩下的部分,如果也查找成功,那就输出。比如“a ahat hat”,”ahat”在字典树中查找时,找到’a’是一个单词,截掉’a’的部分,剩下”hat”,继续找,找到了”hat”,就证明是由两个单词组成的了。
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstring>
#include <malloc.h>
char s[50001][100];
struct Trie
{
int isWord;
Trie *next[26];
};
void Init(Trie *t) //初始化结点
{
t->isWord = 0;
for(int i = 0; i < 26; i++)
{
t->next[i] = NULL;
}
}
void Insert(Trie *t, char s[]) //建树
{
Trie *temp = t;
int len = strlen(s);
for(int i = 0; i< len; i++)
{
if(temp->next[s[i]-'a'] == NULL)
{
temp->next[s[i]-'a'] = (Trie*)malloc(sizeof(Trie));
Init(temp->next[s[i]-'a']);
}
temp = temp->next[s[i]-'a'];
}
temp->isWord = 1;
}
int Search(Trie *t, char s[]) //查找操作
{
Trie *temp = t;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(temp->next[s[i]-'a'] == NULL)
return 0;
temp = temp->next[s[i]-'a'];
}
if(temp->isWord)
{
return 1;
}
return 0;
}
int main()
{
char word[100];
Trie *root = (Trie*)malloc(sizeof(Trie));
Init(root);
int key = 0;
while(gets(word)!=NULL)
{
strcpy(s[key], word);
Insert(root, word);
key++;
}
for(int i = 0; i < key; i++)
{
int len = strlen(s[i]);
for(int j = 1; j < len; j++)
{
char a[100];
strncpy(a, s[i], j);
a[j] = '\0';
if(Search(root, a)) //查找成功了之后
{
char b[100];
strncpy(b, s[i]+j, len-j);
b[len-j] = '\0';
if(Search(root, b)) //截掉前部分,继续查找
{
puts(s[i]); //输出该字符串
break;
}
}
}
}
return 0;
}