【数据结构】·【KMP算法实现】

#include<string>
#include<iostream>
using namespace std;
int KMP(string& pat,string& str,int k,int *next){//返回pat第一次匹配到str的数组位置
	int posP=0;
	int posT=k;
	int lengthP=pat.length();
	int lengthT=str.length();
	while(posP<lengthP && posT<lengthT){
		if(posP==-1 || pat[posP]==str[posT]){
			posP++;
			posT++;
		}
		else
			posP=next[posP];
	}
	if(posP<lengthP)
		return -1;
	else
		return posT-lengthP;
}

void getNext(string& str,int next[]){
	int j=0,k=-1,lengthP=str.length();
	next[0]=-1;
	while(j<lengthP){
		if(k==-1 || str[j]==str[k]){
			j++;
			k++;
			next[j]=k;
		}else
			k=next[k];
	}
}

void main(){
	string str,pat;

	cout<<"输入目标串:";
	cin>>str;
	cout<<"输入模式串:";
	cin>>pat;

	int size=pat.length();
	int *next,k=0;
	next=new int[size];


	getNext(pat,next);
	for(int i=0;i<size;i++){
		cout<<next[i];
	}
	cout<<endl;
	cout<<KMP(pat,str,k,next);
}

运行截图:

用一个辅助数组next[]

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...