最近学习KMP算法,就自己实现了一下试试,因为没有完整的测试过,所以也不知道是不是完全正确,但是本地输入的几个测试样例都过了。。。。。
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
void get_next(string input,int next[])//获取next数组
{
int i=1,j=0;next[0]=0;
while(i < input.size())//相当于自匹配
{
if (j == 0 || input[i] == input[j])
{
i++;j++;
if (input[i] == input[j]) next[i] = next[j];
else next[i] = j-1;
}
else j = next[j];
}
}
bool kmp(string src,string tar)//kmp算法实现
{
int next[tar.size() + 1]{0};
get_next(tar,next);
//for (int i=0;i<tar.size();i++) cout << next[i] << endl;
int i=0,j=0;
while(i < src.size())
{
while(i < src.size() && j < tar.size() && src[i] == tar[j])
{
i++;j++;
}
if (j > tar.size() - 1) return true;
if (j == 0) j++,i++;
else
j = next[j];
}
return false;
/*while(i < src.size() && j < tar.size())
{
if (src[i] == tar[j]) i++,j++;
else j = next[j];
}
if (j >= tar.size()) return true;
else return false;*/
}
int main()
{
string input = "";
cin >> input;
string output = "";
cin >> output;
if (kmp(input,output)) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}