KMP-(POJ 2752)Seek the Name, Seek the Fame

  • KMP-(POJ 2752)Seek the Name, Seek the Fame


KMP算法

    给个传送门,分享下KMP: 串的模式匹配算法-KMP算法

  • 思路:

题目要求的是所有能与给定串前缀和后缀相匹配的子串长度

而规律是从Next数组后往前递归,求得最大符合要求子串(不包括原串),Next[len]的值指向的下一Next值也是符合要求子串的长度,直到Next值小于等于0

KMP性质:下标为IndexNext值表示的是以Str[Index-1]结尾的子串Str的匹配程度,所以Next数组要求到下标为Len,才能获得结尾为Str[Len-1]的串与Str的匹配程度

  • 代码:

#include<iostream>	
#include<cstring>	
using namespace std;
//poj 2752
#define MAXSIZE 400005

int Next[MAXSIZE];
int Answer[MAXSIZE];
int len;

void KMP(char Str[])
{
	int i = 0, k = -1;
	Next[0] = -1;
	while (i < len)
	{
		if (k == -1 || Str[i] == Str[k])
		{
			++i;
			++k;
			Next[i] = k;
		}
		else
			k = Next[k];
	}
}

int main()
{
	char Str[MAXSIZE];
	
	while (cin >> Str)
	{
		len = strlen(Str);
		KMP(Str);
		
		int n = 0, i = len;
		Answer[0] = len;	//最长符合情况的子串是本身!
		while (Next[i] > 0)
		{
			i = Next[i];		//Next[i]表示符合要求子串长度
			Answer[++n] = i;	//记录长度
		}
		for (int i = n; i >= 0; i--)
		{
			cout << Answer[i] << " ";
		}
		cout << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SZU_Crayon/article/details/81409963
今日推荐