这个KMP模板支持连续匹配,如果需要完成其他任务,则可以修改匹配成功后进行的操作
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <memory.h>
#define MAX 10000
using namespace std;
void getNext(char *str,int *next)
{
int j=0,k=-1;//k指向串的前部分,j指向串的后部分
next[0]=-1;//规定
int len=strlen(str);
while(j<len)//扫描串的每一个字符,求出它的next
{
if(k==-1||str[k]==str[j])//如果k为-1或者上一次匹配成功,则k,j指针向后移动
{
k++,j++;
if(str[k]!=str[j])//优化,当这两个字符不相等的时候,那么回溯才是有意义的,因为如果相等回溯过去
{
next[j]=k;
}
else
{
next[j]=next[k];
}
}
else
k=next[k];//如果匹配失败,k回溯到上一个匹配成功的k的下一个位置,因为j向前走了一个位置
}
}
void KMP(char *m_str,char *str)
{
int next[MAX];
getNext(str,next);
int i=0,j=0;//i主串指针,j模式串指针
int m_len,len;
m_len=strlen(m_str);
len=strlen(str);
while(i<=m_len)//之所以取到m_len,是因为可能最后一段匹配成功
{
if(j>=len)//匹配成功后的处理
{
cout<<i-j<<endl;//输出匹配成功的位置
//因为i,j都多走了一步,所以i不用动,j回退到起点
j=0;
}
else if((j==-1||m_str[i]==str[j])&&i<m_len)
{
i++;
j++;
}
else if(i<m_len)
j=next[j];//匹配失败回溯
}
}
int main()
{
char m_str[MAX],str[MAX];
while(cin>>m_str>>str)
{
KMP(m_str,str);
}
return 0;
}