【題目】
【思路】
Trie樹基本應用,先建樹,而後對每個字符串查詢,在查詢過程中,取第一次碰到的尾綴單詞數爲1的結點之前的字符串作爲前綴,如果查詢完都沒有,則取本身爲前綴。
【代碼】
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
char ch;
int num;
struct node *fChild, *rCousin;
}* triNode;
triNode newTree(char t)
{
triNode x=(triNode) malloc(sizeof(struct node));
x->ch=t; x->num=1; x->fChild=NULL; x->rCousin=NULL;
return x;
}
void addTree(triNode x, const char *s, int p)
{
int sLen=strlen(s),i;
for (i=p;i<sLen;i++)
{
x->fChild=newTree(s[i]);
x=x->fChild;
}
}
int main()
{
triNode t=newTree('0');
int total=0,i,j;
char s[21],a[1001][21];
while (scanf("%s",s)!=EOF)
{
strcpy(a[total++],s);
int sLen=strlen(s);
triNode x=t,y;
for (i=0;i<sLen;i++)
{
y=x->fChild;
if (y==NULL) {addTree(x,s,i);break;}
do
{
if (y->ch==s[i]){x=y;x->num++;break;}
x=y; y=y->rCousin;
}while (y!=NULL);
if (y==NULL) {x->rCousin=newTree(s[i]); addTree(x->rCousin,s,i+1); break;}
}
}
for (i=0;i<total;i++)
{
printf("%s ",a[i]);
triNode x=t;
int sLen=strlen(a[i]);
for (j=0;j<sLen;j++)
{
x=x->fChild;
while (1){if (x->ch==a[i][j]) break; else x=x->rCousin;}
printf("%c",x->ch);
if (x->num==1) {printf("\n");break;}
if (j==sLen-1) printf("\n");
}
}
return 0;
}