标签:括号 int into 返回值 ram 实现 使用 class empty
题目:
Input
Input consists of two lines. The first line contains s1 and the second line contains s2. You may assume all letters are in lowercase.
Output
Output consists of a single line that contains the longest string that is a prefix of s1 and a suffix of s2, followed by the length of that prefix. If the longest such string is the empty string, then the output should be 0.
The lengths of s1 and s2 will be at most 50000.
Sample Input
clinton homer riemann marjorie
Sample Output
0 rie 3
题意描述:
输入两个串s1和s2
计算并输出s1串的前缀和s2的后缀的最长相似部分和它的长度
解题思路:
KMP模板题,不同在于让KMP函数匹配过程中让s1跑完,最后返回最相似度j即可。
代码实现:
1 #include<stdio.h> 2 #include<string.h> 3 char s1[50010],s2[50010]; 4 int kmp(char s[],char t[]); 5 void get_next(char t[],int next[],int l); 6 int main() 7 { 8 int i,j,k; 9 while(scanf("%s%s",s1,s2) != EOF) 10 { 11 if( (k=kmp(s2,s1)) > 0 )//加括号 12 { 13 for(i=0;i<k;i++) 14 printf("%c",s1[i]); 15 printf(" %d\n",k); 16 } 17 else 18 printf("0\n"); 19 } 20 return 0; 21 } 22 int kmp(char s[],char t[]) 23 { 24 int i,j,l1,l2; 25 l1=strlen(s); 26 l2=strlen(t); 27 int next[50010]; 28 get_next(t,next,l2); 29 i=0; 30 j=0; 31 while(i < l1) 32 { 33 if(j==-1 || s[i] == t[j]) 34 { 35 i++; 36 j++; 37 } 38 else 39 j=next[j]; 40 } 41 //printf("j=%d\n",j); 42 return j; 43 } 44 void get_next(char t[],int next[],int l) 45 { 46 int i,j; 47 i=0;j=-1; 48 next[0]=-1; 49 while( i < l) 50 { 51 if(j==-1 || t[i]==t[j]) 52 { 53 i++; 54 j++; 55 next[i]=j; 56 } 57 else 58 j=next[j]; 59 } 60 /*for(i=0;i<=l;i++) 61 printf("%d ",next[i]); 62 printf("\n");*/ 63 }
易错分析:
1、注意直接使用函数返回值作为判断时最好将其赋值给一个变量,避免重复调用
HDU 2594 Simpsons’ Hidden Talents
标签:括号 int into 返回值 ram 实现 使用 class empty
原文地址:http://www.cnblogs.com/wenzhixin/p/7344218.html