題目要求要給所有字符串找一個最短的前綴,讓能夠根據這個最短的前綴與其他的字符串區別開,這裏用一個字典樹,每個節點記錄相應字母出現的次數,在建立完字典樹之後查詢的時候遇到1或者字符串遍歷到結尾的時候進行輸出,比較容易的題目。
#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
#define maxp 30
#define maxn 25
#define maxl 1050
struct node{
int Count;
node* p[maxp];
};
char str[maxl][maxn];
int loc = 0;
void insert(node *root,int loc,int k,int len){
root->Count++;
if(k==len)
return;
int Temp = (int)(str[loc][k]-'a');
node *tp = (root->p)[Temp];
if(!(root->p)[Temp]){
tp = (root->p)[Temp] = new node;
tp->Count = 0;
memset(tp->p,0,sizeof(tp->p));
}
//printf("count: %d\n",root->Count);
insert(tp,loc,k+1,len);
}
void check(node *root,int loc,int k,int len){
if(root->Count == 1 || k==len){
printf("%s ",str[loc]);
for(int i=0;i<k;++i){
printf("%c",str[loc][i]);
}
printf("\n");
return;
}
int Temp = (int)(str[loc][k]-'a');
check((root->p)[Temp],loc,k+1,len);
}
int main(){
node *root = new node;
root->Count = 0;
memset(root->p,0,sizeof(root->p));
while(scanf("%s",&str[loc])!=EOF){
/*char h=cin.get();
h = cin.peek();
if(h=='\n')
break;*/
int len = strlen(str[loc]);
//printf("%s\n",str[loc]);
insert(root,loc,0,len);
loc++;
}
for(int i=0;i<loc;++i){
int len = strlen(str[i]);
check(root,i,0,len);
}
//system("pause");
return 0;
}