void get_next(string S, int* next)
{
next[0] = 0;//初始化为0
int j = 0, i = 1;//j前缀末尾,i后缀末尾
cout << next[0] << " ";
for (i = 1; i < S.length(); i++)
{
while (j > 0 && S[i] != S[j])//不相等情况
{
j = next[j - 1];//回溯next数组
}
if (S[i] == S[j])//相等情况
{
j++;
}
next[i] = j;//跟新next数组
cout << next[i] << " ";
}
}
void KMP(string S, string T, int next[])
{
int len = 0, i = 0, j = 0;
for (i = 0; i < S.size(); i++)
{
while (j > 0 && T[j] != S[i])
{
j = next[j-1];//j往前回溯
}//直到匹配到想等的
if ( S[i] == T[j])
{
j++;//相等则加j
}
if (j == T.size())
{
cout << i - T.size() + 2 << endl;
j = next[j - 1];
}
}
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
int next[1000] = { 0 };
next[0] = 0;//初始化为0
int j = 0, i = 1;//j前缀末尾,i后缀末尾
for (i = 1; i < s2.size(); i++)
{
while (j > 0 && s2[i] != s2[j])//不相等情况
{
j = next[j - 1];//回溯next数组
}
if (s2[i] == s2[j])//相等情况
{
j++;
}
next[i] = j;//跟新next数组
}
KMP(s1, s2, next);
//打印next数组
for (int i = 0; i < s2.size(); i++)
{
cout << next[i] << " ";
}
return 0;
}
KMP算法
最新推荐文章于 2025-05-09 22:36:54 发布