您的位置:首页 > 其它

hihoCoder 1015 kmp算法

2016-04-09 22:31 453 查看
入门题= =

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int MAX = 1e4 + 5;
int nex[MAX];
char str[MAX], p[100 *MAX];

void get_nex(char* arr, int* nex)
{
int k = -1, j = 0;
nex[j] = k;
int lenth = strlen(arr);
while (j < lenth)
{
if (k == -1 || arr[j] == arr[k])
{
++j;
++k;
if (arr[j] == arr[k])
nex[j] = nex[k];
else
nex[j] = k;
}
else
{
k = nex[k];
}
}
}

int kmp(char* p, char* str)
{
get_nex(str, nex);
int res = 0;
int lenth1 = strlen(p);
int lenth2 = strlen(str);
int i = 0, j = 0;
while (i < lenth1)
{
if (j == -1 || p[i] == str[j])
{
i++;
j++;
if (j == lenth2)
{
//j = 0;
res++;
j = nex[j];
}
}
else
{
j = nex[j];
}
}
return res;
}

int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(nex, 0, sizeof(nex));
scanf("%s%s", str, p);
printf("%d\n", kmp(p, str));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: