字典树入门题......
只需在对应结点记录num值,找到num为1时的前缀,是唯一前缀(只是该单词的前缀),或者一直找找到该单词结尾。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 1050
#define INF 0x7FFFFFFF
# define eps 1e-5
//#pragma comment(linker, "/STACK:36777216") ///传说中的外挂
using namespace std;
char s[1005][25];
char ss[25];
struct node
{
node *next[30];
int num;
node ()
{
num=0;
for(int i=0; i<26; i++)
next[i] = NULL;
}
} * root;
void insert(char *s)
{
node *p = root;
int i,len;
len = strlen(s);
for(i=0; i<len; i++)
{
int v = s[i] - 'a';
if(p->next[v] == NULL)
{
p->next[v] = new node;
}
p->next[v]->num ++;
p = p->next[v];
}
}
void *search(char *s)
{
node *p = root;
int q=0,i;
int len = strlen(s);
for(i=0; i<len; i++)
{
ss[q++] = s[i];
int v = s[i] - 'a';
if(p->next[v]->num == 1) // 该字母在当前层数只出现过一次
{
ss[q] = '\0';
return ss;
}
p = p->next[v];
}
ss[q] = '\0';
return ss;
}
int main()
{
int i=0;
root = new node;
while(cin >> s[i])
insert(s[i++]);
for(int j=0; j<i; j++)
{
printf("%s %s\n",s[j],search(s[j]));
}
return 0;
}