#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int mynext[100];//next数组
int count1 = 0;//匹配到几个子串
void GetNext( string a)//本质就是找最大的相同的前缀后缀长度
{
int n = a.size();
mynext[0] = -1;
int j = 0;
int k = -1;
while (j < n)
{
if (k == -1 || a[j] == a[k])
{
j++;
k++;
mynext[j] = k;
}
else
{
k = mynext[k];
}
}
}
void KMP(string s1,string s2)
{
int l1 = s1.size();
int l2 = s2.size();
GetNext(s2);
int i = 0;
int j = 0;
while (i < l1)
{
if (j==-1||s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = mynext[j];//当不相同时,移动s2
}
if (j == l2)
{
count1++;
j = 0;
}
}
}
int main()
{
string s1 = "ababcabcabcd";
string s2 = "abc";
KMP(s1, s2);
cout<<count1<<endl;
}
KMP C++代码
最新推荐文章于 2024-08-07 17:27:15 发布