写法一:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int count;
struct node *next[26];
};
struct node *root,*p,*q;
char s[1010][25];
int main(){
int i,j,k,m,n=0;
root=new node;
root->count=0;
for(i=0;i<26;i++)root->next[i]=NULL;
while(scanf("%s",&s[++n])!=EOF){
p=root;
k=strlen(s[n]);
for(i=0;i<k;i++){
if(p->next[s[n][i]-'a']==NULL){
q=new node;
q->count=1;
for(j=0;j<26;j++)q->next[j]=NULL;
p->next[s[n][i]-'a']=q;
p=q;
}else{
p=p->next[s[n][i]-'a'];
p->count++;
}
}
}
for(i=1;i<=n;i++){
printf("%s ",s[i]);
p=root;
k=strlen(s[i]);
for(j=0;j<k;j++){
p=p->next[s[i][j]-'a'];
printf("%c",s[i][j]);
if(p->count==1)break;
}
printf("\n");
}
return 0;
}
写法二:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
int count;
struct node *next[26];
node(){
count=0;
memset(next,0,sizeof(next));
}
};
struct node *root,*p,*q;
char s[1010][25];
void insert(char *st){
int i,j,k;
p=root;
k=strlen(st);
for(i=0;i<k;i++){
if(p->next[st[i]-'a']==NULL){
q=new node;
p->next[st[i]-'a']=q;
}
p=p->next[st[i]-'a'];
p->count++;
}
}
void search(char *st){
int i,j,k;
p=root;
k=strlen(st);
for(i=0;i<k;i++){
p=p->next[st[i]-'a'];
printf("%c",st[i]);
if(p->count==1)break;
}
}
int main(){
int i,j,k,m,n=0;
root=new node;
while(scanf("%s",&s[++n])!=EOF)
insert(s[n]);
for(i=1;i<=n;i++){
printf("%s ",s[i]);
search(s[i]);
printf("\n");
}
return 0;
}