I'll give you two strings. The length of the string that contains the two strings is used to make a pattern string and a text string, respectively, and then to match the condition.
#include <stdio.h> #include <string.h> #include <iostream>using namespaceStd; Char Str1[1000010],str2[1000010],Str3[1000010]; int Next[1000010]; int Deal (char Str [],int Len){Memset(Next,0 ,sizeof( Next));Next[0]=-1; int I=0,K=-1; while (I<Len-1 ) { if( K==-1||Str[I]==Str[K]) {I++;K++;Next[I]=K; } Else K=Next[K]; } return 0;} int Find (char Str1 [],Char str2 [],int Len1 ,int Len2 ) { int I,J;I=0,J=0; int K=-1; while (J<Len2&&I<Len1 ) { if( Str1[I]==str2[J]||J==-1) {I++;J++; if (J>K&&I==Len1||J==Len2)K=J ;//Pay attention to the line} Else J=Next[J]; } return K;} int Main () { int T,I,J,T;scanf("%d",&T); while (T --) { int Max=-1;scanf("%s%s",Str1,str2); int Len1=Strlen(Str1); int Len2=Strlen(str2);Deal(str2,Len2); int T=Find(Str1,str2,Len1,Len2);Max=Max<T?T:Max;Deal(Str1,Len1);T=Find(str2,Str1,Len2,Len1);Max=Max<T?T:Max;Printf("%d\n",Len1+Len2-Max); } return 0;}
HDU 1841 KMP Application