跳到正文

题解

题解 P3375 【【模板】KMP字符串匹配】

yybyyb约 3 分钟
原文

这是 2026年1月14日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2017年7月10日
收录
2026年1月14日
更新
2026年11月10日
篇幅
约 3 分钟
题目
P3375

版本

  1. v2当前
  2. v1

KMP是一个优秀的字符串算法(不优秀我们干嘛要学)

然后,这就是一个裸的模板。。。

如果Next数组理解不是很好的话,我写了篇博客~~(尽管可能讲的依旧不是很清楚)~~

地址:http://blog.csdn.net/qq_30974369/article/details/74276186

对于KMP,不理解的请多多手算

理解了next数组,KMP就变得十分简单(跟AC自动机理解了失配指针一样)

C++
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX=1001;
int Next[MAX];
vector<int> Ans;
inline void GetNext(string s)//获得字符串s的next数组
{
    int l=s.length(),t;
    Next[0]=-1;//如果在0位置失配则是向下移动一位
    for(int i=1;i<l;++i)//依次求解后面的next数组
    {
        t=Next[i-1];
        while(s[t+1]!=s[i]&&t>=0)
            t=Next[t];
        if(s[t+1]==s[i])
            Next[i]=t+1;
        else
            Next[i]=-1;
    }
}
inline void KMP(string s1,string s2)
{
    GetNext(s2);
    int l1=s1.length();
    int l2=s2.length();
    int i=0,j=0;
    while(j<l1)
    {
        if(s2[i]==s1[j])//当前位匹配成功,继续匹配下一位
        {
            ++i;++j;
            if(i==l2)//完全匹配
            {
                Ans.push_back(j-l2+1);//储存答案
                i=Next[i-1]+1;//继续匹配                
            }
        }
        else
        {
            if(i==0)//在首位不匹配
                j++;
            else
                i=Next[i-1]+1;
        }
    }
}
int main()
{
    string s1,s2;
    int l;
    cin>>s1>>s2;
    l=s2.length();
    KMP(s1,s2);
    for(int i=0;i<Ans.size();++i)
        cout<<Ans[i]<<endl;
    for(int i=0;i<l;++i)
        cout<<Next[i]+1<<' ';
    cout<<endl;
    return 0;
}