# ＫＭＰ poj 3461

找一个模式串在主串中出现的次数

#include <iostream>
#include <cstring>

using namespace std;

const int MAXN = 1000010;
const int MAXM = 10010;

int nextval[MAXM];

void Get_NextVal(char* str)
{
int len = strlen( str );
int i = 0, j = -1;
nextval[0] = -1;
while (i < len)
{
if (j == -1 || str[i] == str[j])
{
++i;
++j;
if(str[i] == str[j])
nextval[i] = nextval[j];
else
nextval[i] = j;
}
else
j = nextval[j];
}
}

int KMP(char* str1, char* str2)
{
int i = 0, j = 0;
int ans = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
Get_NextVal(str1);
while (i < len2)
{
if (j == -1 || str1[j] == str2[i])
{
++i;
++j;
}
else
j = nextval[j];
if(j >= len1)
{
ans++;
j = nextval[j];//这里不是从模式串的首部从新开始，而是从他的nextval开始
}
}
return ans;
}

int main()
{
int T;
cin>>T;
char str1[MAXM], str2[MAXN];
while (T--)
{
cin>>str1;
cin>>str2;
int sum = 0;
sum = KMP(str1, str2);
cout<<sum<<endl;
}
return 0;
}


#### POJ 3461(模式匹配数&覆盖函数）

2012-11-15 08:22:13

#### POJ 3461 kmp 应用

2014-04-19 11:07:07

#### 【哈希&KMP模板题】-POJ-3461-Oulipo

2014-04-26 15:54:18

#### POJ3461 字符串HASH

2015-08-09 12:38:01

#### hdu 3461 Code Lock(并查集+二分求幂)

2013-01-29 12:22:30

#### hdu3461Code Lock【并查集+快速幂】

2015-10-09 21:22:02

#### ＫＭＰ

2014-07-27 15:01:25

#### poj 3461

2014-04-08 16:14:51

#### POJ 3461

2014-04-18 16:57:02

#### poj 3461

2014-03-19 22:51:24