洛谷 [模板]KMP字符串匹配

又水了一篇
题目链接:https://www.luogu.com.cn/problem/P3375

#include<bits/stdc++.h>
using namespace std;
int Next[1000010]={0};
void getNEXT(string str)
{
    Next[0] = -1;
    int i=-1, j=0;
    while(j < str.size())
    {
        if(i==-1 || str[j]==str[i])
        {
            i++;
            j++;
            Next[j] = i;
        }
        else i = Next[i];
    }
}
void KMP(string str1, string str2)
{
    int i=0, j=0;
    int len1=str1.size(), len2=str2.size();
    while(i<len1)
    {
        if(j==-1 || str1[i]==str2[j])
        {
            i++;
            j++;
        }
        else j = Next[j];
        if(j == len2)
        {
            cout<<i-j+1<<endl;
            i--;
            j = 0;
            //j = Next[j];
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    string s1, s2;
    cin>>s1>>s2;
    getNEXT(s2);
    KMP(s1, s2);
    for(int i=1; i<=s2.size(); i++)
        cout<<Next[i]<<" ";
    return 0;
}

发布了65 篇原创文章 · 获赞 50 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_41248654/article/details/104804807