思路:与普通的字典树不同的是,该题 我们需要把一个单词拆分成两个单词,例如:bbccc 可以拆分成:b bccc等等。然后判断拆分后的两个单词是不是在字典树中。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stdlib.h>
using namespace std;
struct dirtree
{
struct dirtree *child[26];
bool vis;
};
char word[50000][100];
struct dirtree *root;
void BuildTree(char *word)
{
int len=strlen(word);
struct dirtree *Root,*tem;
Root=root;
for(int i=0;i<len;i++)
{
if(Root->child[word[i]-'a']==0)
{
tem=(struct dirtree *)malloc(sizeof(struct dirtree));
for(int j=0;j<26;j++)
{
tem->child[j]=0;
}
tem->vis=false;
Root->child[word[i]-'a']=tem;
}
Root=Root->child[word[i]-'a'];
}
Root->vis=true;
}
bool find(char *word)
{
int len=strlen(word);
struct dirtree *Root;
Root=root;
for(int i=0;i<len;i++)
{
if(Root->child[word[i]-'a']!=0)
{
Root=Root->child[word[i]-'a'];
}
else
return false;
}
if(Root->vis)
return true;
else
return false;
}
//单词拆分:
int main()
{
int len=0;
char tem1[100],tem2[100];
root=(struct dirtree *)malloc(sizeof(struct dirtree));
for(int i=0;i<26;i++)
{
root->child[i]=0;
}
root->vis=false;
while(scanf("%s",word[len])!=EOF)
{
BuildTree(word[len]);
len++;
// if(strcmp(word[len-1],"zhuhao")==0)
// break;
}
for(int i=0;i<len;i++)
{
int Len=strlen(word[i]);
for(int j=0;j<Len-1;j++)
{
int aL=0,bL=0;
for(int k=0;k<=j;k++)
{
tem1[aL]=word[i][k];
aL++;
}
for(int n=j+1;n<Len;n++)
{
tem2[bL]=word[i][n];
bL++;
}
tem1[aL]=tem2[bL]='\0';
if(find(tem1)&&find(tem2))
{
printf("%s\n",word[i]);
break;
}
memset(tem1,0,sizeof(tem1));
memset(tem2,0,sizeof(tem2));
}
}
return 0;
}