KMP算法求在给定字符串中与查询字符串匹配的个数

题目:给定一个文本字符串和查询字符串,找出在文本字符串中与查询字符串匹配的个数

思路:利用KMP算法,求出查询字符串的next数组,之后在文本字符串中进行查询

代码:

#include <iostream>
#include <string>
using namespace std;

//KMP算法得到匹配的个数
int KMPCount(char* strTarget,char* strPattern,int next[])
{
	assert(strTarget != NULL && strPattern != NULL && next != NULL);

	int nCurT = 0;
	int nCurP = 0;

	int nCount = 0;

	int nTargetLen = strlen(strTarget);
	int nPatternLen = strlen(strPattern);

	while (nCurT < nTargetLen)
	{
		if (nCurP == nPatternLen)
		{
			nCount++;
			nCurP = next[nCurP];
		}
		else if (nCurP < nPatternLen)
		{
			if (nCurP == -1 || strTarget[nCurT] == strPattern[nCurP])
			{
				nCurT++;
				nCurP++;
			}
			else
			{
				nCurP = next[nCurP];
			}
		}
	}

	return nCount;
}

void GetNext_Count(char* strPattern,int next[])
{
	assert(strPattern != NULL && next != NULL);

	int nCurP = 1;
	int nLastPos = -1;
	next[0] = -1;

	int nPatternLen = strlen(strPattern);

	while (nCurP <= nPatternLen)
	{
		if (nLastPos == -1 || strPattern[nCurP-1] == strPattern[nLastPos])
		{
			nLastPos++;
			next[nCurP] = nLastPos;
			nCurP++;
		}
		else
		{
			nLastPos = next[nLastPos];
		}
	}
}

int main()
{
	char strTarget[50];
	cout<<"input target string:";
	cin>>strTarget;

	char strPattern[20];
	cout<<"input strPattern string:";
	cin>>strPattern;

	int nPatternLen = strlen(strPattern);

	//求匹配字符串的匹配个数

	//多存放一位,表示当匹配成功时匹配字符串向后移动的位置
	int* next_count = new int[nPatternLen+1];

	GetNext_Count(strPattern,next_count);

	int nPatternCount = KMPCount(strTarget,strPattern,next_count);

	if (nPatternCount == -1)
	{
		cout<<"No Pattern!"<<endl;
	}
	else
	{
		cout<<"Pattern count is :"<<nPatternCount<<endl;
	}

	delete[] next_count;
	system("pause");
	return 0;
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/ziyouzhongdexiyan/article/details/39208175
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞