串的模式匹配KMP算法

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

//next函数值算法
void getNext(string substr,int next[])
{
	int i=0,j=-1;
	next[0] = -1;
	while(i<substr.length()-1)
	{
		if(j==-1||substr[i]==substr[j])
		{
			i++;
			j++;
			next[i]=j;
		}
		else
		{
			j=next[j];
		}
	}
}

//改进后的next函数值算法
void getNextVal(string substr,int nextval[])
{
	int i=0,j=-1;
	nextval[0] = -1;
	while(i<substr.length()-1)
	{
		if(j==-1||substr[i]==substr[j])
		{
			i++;
			j++;
			if(substr[i]!=substr[j])
			{
				nextval[i]=j;
			}
			else
			{
				nextval[i]=nextval[j];
			}
		}
		else
		{
			j=nextval[j];
		}
	}
}

//KMP算法主函数
int indexKMP(string mainstr,string substr,int pos)
{
	const int SIZE = 50;
	int i=pos,j=0;
	int next[SIZE];

	getNext(substr,next);//或者调用getNextVal(substr,next);
	while(i<(int)mainstr.length()&&j<(int)substr.length())	
	{
		if(j==-1||mainstr[i]==substr[j])
		{
			i++;
			j++;
		}
		else
		{
			j=next[j];
		}
	}
	if(j>=substr.length())
	{
		return i-substr.length();
	}
	return -1;
}

int main()
{
	string mainStr = "wrsdsegegf ffsegeggs";
	string subStr = "segeggs";
		
	int pos = indexKMP(mainStr, subStr, 0);

	cout<<pos<<endl;
	cin.get();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yycdaizi/article/details/7251494