【KMP nx数组】J - Simpsons’ Hidden Talents HDU - 2594

Simpsons’ Hidden Talents

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14087    Accepted Submission(s): 4847


 

Problem Description


Write a program that, when given strings s1 and s2, finds the longest prefix of s1 that is a suffix of s2.

 

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

 

Source

HDU 2010-05 Programming Contest

#include <bits/stdc++.h>
using namespace std;

const int mn = 50010;

char s1[2 * mn], s2[mn];
int nx[2 * mn];

void cal_next(char ch[], int len)
{
	nx[0] = -1;
	int k = -1;
	for (int i = 1; i < len; i++)
	{
		while (k > -1 && ch[k + 1] != ch[i])
			k = nx[k];
		if (ch[k + 1] == ch[i])
			k++;
		nx[i] = k;
	}
}

int main()
{
	#ifndef ONLINE_JUDGE
		freopen("C:\\in.txt", "r", stdin);
	#endif // ONLINE_JUDGE

	while (~scanf("%s%s", s1, s2))
	{
		int slen = strlen(s1);
		int tlen = strlen(s2);
		strcat(s1, s2); // s2 合并到 s1 后, 两倍内存
		int len = strlen(s1);

		cal_next(s1, len);
		// 找最长前后缀

		if (nx[len - 1] == -1)
			printf("0\n");
		else
		{
			int temp = min(nx[len - 1] + 1, slen);
			temp = min(temp, tlen);
			// 保证是两串的子串

			for (int i = 0; i < temp; i++)
				printf("%c", s1[i]);
			printf(" %d\n", temp);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ummmmm/article/details/82229389
今日推荐