KMP

来源:互联网 发布:php程序员开发软件 编辑:程序博客网 时间:2024/06/18 17:45

Problem Description

Generally speaking, there are a lotof problems about strings processing. Now you encounter another such problem.If you get two strings, such as “asdf” and “sdfg”, the result of the additionbetween them is “asdfg”, for “sdf” is the tail substring of “asdf” and the headsubstring of the “sdfg” . However, the result comes as “asdfghjk”, when youhave to add “asdf” and “ghjk” and guarantee the shortest string first, then theminimum lexicographic second, the same rules for other additions.

Input

For each case, there are two strings(the chars selected just form ‘a’ to ‘z’) for you, and each length of theirswon’t exceed 10^5 and won’t be empty.

Output

Print the ultimate string by thebook.

Sample Input

asdf sdfg
asdf ghjk

Sample Output

asdfg
asdfghjk
 

 

给出两个字符串,要求将其组合起来,首先保证组合后的长度最短,然后按照字典序最小的方式组合,并且保证组合后两个字符串中重复的部分去掉

KMP,组合有两种方式一个在前一个在前,为了满足规则,首先求出两种不同组合方式后前缀和后缀的长度,比较哪个字符串放在前面,若长度相同则用strcmp函数比较字典序决定哪个字符串放在前面



#include<stdio.h>#include<string.h>char a[200110],b[200010],c[100010],d[100010];int next[200010],next1[200010],lena,lenb;int get_next(){int i=1,j=0;next[0]=0;while(i<lena){if(j==0 && a[i]!=a[j]){next[i]=0;i++;}else if(j>0 && a[i]!=a[j])j=next[j-1];else{next[i]=j+1;i++;j++;}}return next[lena-1];}int get_next1(){int i=1,j=0;next1[0]=0;while(i<lenb){if(j==0 && b[i]!=b[j]){next1[i]=0;i++;}else if(j>0 && b[i]!=b[j])j=next1[j-1];else{next1[i]=j+1;i++;j++;}}return next1[lenb-1];}int main(){int s,s1,i,lenc,lend;while(scanf("%s",a)!=EOF){scanf("%s",b);strcpy(c,a);strcpy(d,b);strcat(a,b);strcat(b,c);lena=strlen(a);lenb=strlen(b);lenc=strlen(c);lend=strlen(d);s=get_next();s1=get_next1();//printf("%d %d\n",s,s1);if(s>s1){for(i=0;i<lend-next[lena-1];i++)printf("%c",d[i]);printf("%s\n",c);}else if(s<s1){for(i=0;i<lenc-next1[lenb-1];i++)printf("%c",c[i]);printf("%s\n",d);}else{if(strcmp(c,d)<0){for(i=0;i<lenc-next[lena-1];i++)printf("%c",c[i]);printf("%s\n",d);}else{for(i=0;i<lend-next1[lenb-1];i++)printf("%c",d[i]);printf("%s\n",c);}}memset(a,0,sizeof(a));memset(b,0,sizeof(b));memset(next,0,sizeof(next));memset(next1,0,sizeof(next1));}return 0;}


原创粉丝点击