Description
In the sample input below, "carbohydrate" can be abbreviated to "carboh", but it cannot be abbreviated to "carbo" (or anything shorter) because there are other words in the list that begin with "carbo".
An exact match will override a prefix match. For example, the prefix "car" matches the given word "car" exactly. Therefore, it is understood without ambiguity that "car" is an abbreviation for "car" , not for "carriage" or any of the other words in the list that begins with "car".
Input
Output
Sample Input
carbohydrate cart carburetor caramel caribou carbonic cartilage carbon carriage carton car carbonate
Sample Output
carbohydrate carboh cart cart carburetor carbu caramel cara caribou cari carbonic carboni cartilage carti carbon carbon carriage carr carton carto car car carbonate carbona
判斷最短的惟一子串
比如說carbohydrate
而下面有carbonic
因爲題目要求的是唯一的子串
所以只要到相同下一個
就是i惟一子串了
計算每個單詞的每個字母出現的次數
當找尋的時候 字母計數爲1時
也就是隻有他本身
輸出即可
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
struct node
{
int cnt;
node *s[26];
node()
{
memset(s,0,sizeof(s));
cnt=0;
}
};
node *root;
void build(char *s)
{
node *p=root;
int i,len=strlen(s);
for(i=0;i<len;i++)
{
if(p->s[s[i]-'a']==NULL)
p->s[s[i]-'a']=new node;
p=p->s[s[i]-'a'];
p->cnt++;
}
}
int find_str(char *s)
{
node *p=root;
int i,len=strlen(s);
for(i=0;i<len;i++)
{
if(p->cnt==1)//(p->s[s[i]-'a']==NULL)
return 1;
p=p->s[s[i]-'a'];
}
return 0;
}
int main()
{
root=new node;
char s[1111][111];
int k=0,i,l;
while(~scanf("%s",&s[k]))
{
build(s[k]);
k++;
}
for(l=0;l<k;l++)
{
printf("%s ",s[l]);
char ss[111];
int r=0;
for(i=0;s[l][i];i++)
{
ss[r++]=s[l][i];
ss[r]='\0';
int a=find_str(ss);
if(a)
{
ss[r-1]='\0';
cout<<ss<<endl;
break;
}
}
if(s[l][i]=='\0')
printf("%s\n",s[l]);
}
return 0;
}