KMP算法c++实现

时间:2021-09-29 19:59:28

一、原理看下面视频

http://baidu.ku6.com/watch/1196605033445674118.html?page=videoMultiNeed


二、c++代码:

#include<iostream>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;

void get_next(string s1, int next[]){
int len = s1.size();
next[0] = 0;
int i=1;
int j=0;
while(i<len){
if(s1[i] == s1[j]){
next[i] = j+1;
i++;
j++;
}else{
while(j>0 && s1[i]!=s1[j]){
j = next[j-1];
}
if(s1[i] == s1[j]){
next[i] = j+1;
i++;
j++;
}else if(j == 0 && s1[i] != s1[j]){
next[i] = 0;
i++;
}
}
}

}

bool kmpAlgorithm(string s1, string s2, int next[]){
//s1是主串,求s2是否能在s1中模糊匹配出来
int len1 = s1.size();
int len2 = s2.size();
//next的长度和s2的长度是一样的
int j=0; //i用来遍历s1,j用来遍历s2

for(int i=0;i<len1;i++){
while(j>0 && s1[i]!= s2[j]){
j = next[j];
}
if(s1[i] == s2[j]){
j++;
}
if(j == len2){
return true;
}
}

return false;
}



int main(){
string s1,s2;
while(cin>>s1>>s2){
//s1是主串,s2是要判断的串
int *next = new int[s2.size()+1];
get_next(s2, next);
cout<<s1<<endl;
cout<<s2<<endl;
cout<<kmpAlgorithm(s1, s2, next)<<endl;
}

return 0;
}

next数组的测试用例

s字符串: aabaabaaa

next数组:010123452

s字符串:abcaby

next数组:000120