#include<iostream>
#include<string>
using namespace std;
//BF查询
int BF(string S, string T, int pos)//S为主串,T为模式串,pos为查询位置
{
int i = pos;
int j = 0;
while (i < S.length() && j < T.length())
{
if (S[i] == T[j]) {
i++;
j++;
}
else
{
i = i - j + 1;//i++
j = 0;
}
}
if (j >= T.length())
{
return i - T.length();
}
else
{
return -1;
}
}
//BF查询
void Next(string T, int next[])//求前后缀
{
int i = 0,j=-1;
next[0] = -1;
while (i<(int)T.length()-1)
{
if (j == -1 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
//KMP
int KMP(string S, string T, int pos)
{
//static int len = T.size();
int next[20] = { -1 };
Next(T, next);
int i = pos;
int j = -1;
while (i < (int)S.length() && j < (int)T.length())
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j >= (int)T.length())
{
return i - T.length();
}
return 0;
}
int main()
{
string name = "acabaabaabcacaabc";
string first = "abaabcac";
cout << BF(name, first, 0) << endl;
cout << KMP(name, first, 0);
return 0;
}
KMP查找
最新推荐文章于 2023-01-19 10:54:18 发布