Simpsons’ Hidden Talents
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 10278 Accepted Submission(s): 3579
Marge: Yeah, what is it?
Homer: Take me for example. I want to find out if I have a talent in politics, OK?
Marge: OK.
Homer: So I take some politician’s name, say Clinton, and try to find the length of the longest prefix
in Clinton’s name that is a suffix in my name. That’s how close I am to being a politician like Clinton
Marge: Why on earth choose the longest prefix that is a suffix???
Homer: Well, our talents are deeply hidden within ourselves, Marge.
Marge: So how close are you?
Homer: 0!
Marge: I’m not surprised.
Homer: But you know, you must have some real math talent hidden deep in you.
Marge: How come?
Homer: Riemann and Marjorie gives 3!!!
Marge: Who the heck is Riemann?
Homer: Never mind.
Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.
The lengths of s1 and s2 will be at most 50000.
clinton homer riemann marjorie
0 rie 3
题意:读入串1和串2,输出串2的前缀和串1的后缀最长公共部分和长度。
思路:将串1作为子串s2,串2作为主串s1,套用kmp.
#include<stdio.h> #include<string.h> #define N 50010 char s1[N],s2[N]; int next[N],l1,l2; void get_next() { int j,k; j = 0; next[0] = k = -1; while(j < l2) { if(k==-1||s2[j]==s2[k]) next[++j] = ++k; else k = next[k]; } return; } void kmp() { int i,j,k; i = j = 0; while(i < l1) { if(j == -1||s1[i]==s2[j]) { i++; j++; } else j = next[j]; } if(!j)//当s1的后缀和s2前缀不匹配时 printf("0\n"); else { for(k = 0; k < j; k ++)//j是能匹配到s2前缀的长度 printf("%c",s2[k]); printf(" %d\n",j); } return; } int main() { while(scanf("%s %s",s2,s1)!=EOF) {//读入时,将第二行字符串作为主串,第一行字符作为子串 l1 = strlen(s1); l2 = strlen(s2); get_next();//建立next数组 kmp();//字符串前后缀匹配 } return 0; }
709




被折叠的 条评论
为什么被折叠?



