1.C++实现KMP算法模板

其他经典算法合集

https://blog.csdn.net/qq_41562704/article/details/86441022

txt为待查找字符串,pat为子字符串

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string pat,txt;
int N,M;
std::vector<int> Next;
void getNext(){
	int i=-1,j=0;
	Next[0]=-1;
	while(j<M){
		if(i==-1||pat[i]==pat[j]){
			i++;j++;
			Next[j]=i;
		}
		else
			i=Next[i];
	}
}
int KMP(){
	int i=0,j=0;
	while(i<N&&j<M){
		if(j==-1||txt[i]==pat[j]){
			++i;++j;
		}
		else
			j=Next[j];
	}
	if(j==M)
		return i-j;
	return -1;
}
int main(){
	cin>>txt>>pat;
	N=txt.length();M=pat.length();
	Next.resize(M);
	getNext();
	return KMP();
}

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86441406