【kmp算法】C++代码实现

推荐先在B站搜索KMP看一个印度小哥讲解的视频:

https://www.bilibili.com/video/BV1Ys411d7yh

【强烈推荐,看一两遍就懂了】

代码借鉴:

http://blog.csdn.net/weixin_41106545/article/details/83573340

//KMP substring search

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

//以下即NEXT数组的实现 vector
<int> getTempArray(string pattern){ vector<int> result;//声明返回的vector if(pattern.size()==0 || pattern.size()==1){ return result; //如果字符串的长度为0,直接返回空的vector //如果字符串的长度为1,直接返回此时的vector } result.push_back(0);//首先压入0 int j=0; int i=1; while(j < pattern.size()-1 && i <= pattern.size()-1){ if(pattern[i] == pattern[j]){ result.push_back(j+1); i++; j++; } else{ if(j==0){ result.push_back(0); i++; } else{ while(j>=1 && pattern[i] != pattern[j]){ j = result[j-1]; } if(pattern[i] == pattern[j]){ result.push_back(j+1); i++; j++; } else{ result.push_back(0); j++; } } } } return result; } int kmp (string t, string p)//t:text p:pattern { vector<int> next = getTempArray(p); int j=0; for (int i=0; i<t.length(); i++){ while(j>0 && t[i] != p[j]){ j=next[j-1]; } if(t[i] == p[j]){ j++; } if(j==p.length()){ return i-p.length()+1; } } return -1; } int main(){ string str; cout << "Enter the string:"; cin >> str; string pattern; cout << "Enter the pattern:"; cin >> pattern; int result = kmp(str,pattern); if (result == -1){ cout << "Can't find pattern in the string!\n"; } else{ cout << result << endl; } }

 

 

 

 

posted @ 2020-09-22 21:35  马猴烧酒孟优秀  阅读(309)  评论(0编辑  收藏  举报