您的位置:首页 > 编程语言 > C语言/C++

KMP算法c++实现

2017-03-16 21:44 357 查看
一、原理看下面视频

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: