HDU 2594 (KMPnext数组的应用)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2594
题意:给两个字符串,求前面哪个字符串的前缀和后面字符串的后缀相同的最大串。
题解:将两个字符串合成一个字符串,利用KMP里的next数组。next[len]即为所求。但要注意,长度必须小于两者小的那个。
代码如下:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 const int maxn = 50005; 7 char s1[maxn],s2[maxn],s[maxn<<1]; 8 int Next[maxn<<1]; 9 void getNext(int len) 10 { 11 int i = 0,j = -1; 12 Next[0] = -1; 13 while(i<len) 14 { 15 if(j==-1||s[i]==s[j]) 16 { 17 i++; 18 j++; 19 Next[i]=j; 20 } 21 else 22 j=Next[j]; 23 } 24 } 25 26 int main() 27 { 28 while(~scanf("%s%s",s1,s2)) 29 { 30 int len1,len2; 31 len1=strlen(s1); 32 len2=strlen(s2); 33 strcpy(s,s1); 34 strcat(s,s2); 35 int l = len1 + len2; 36 getNext(l); 37 int minn; 38 if(len1<len2) 39 minn=len1; 40 else 41 minn=len2; 42 if(Next[l]>=minn) 43 Next[l]=minn; 44 if(Next[l]) 45 { 46 for(int i=0;i<Next[l];i++) 47 printf("%c",s[i]); 48 printf(" %d\n",Next[l]); 49 } 50 else 51 printf("0\n"); 52 } 53 }
浙公网安备 33010602011771号