您的位置:首页 > 其它

POJ 3461 Oulipo(模式串在主串中出现的次数)

2015-04-27 15:51 393 查看
题目链接:http://poj.org/problem?id=3461

题意:给你两个字符串word和text,求出word在text中出现的次数

思路:kmp算法的简单应用,遍历一遍text字符串即可,当前匹配的字符数达到word字符串的长度,即可确定word字符串出现一次了。

code:

#include <cstdio>
#include <cstring>
using namespace std;
const int MAXM = 10005;
const int MAXN = 1000005;
char word[MAXM];
char text[MAXN];
int next[MAXM];
void GetNext()
{
int len = strlen(word);
int i = 0;
int j = -1;
next[0] = -1;
while (i < len)
{
if (-1 == j || word[i] == word[j]) next[++i] = ++j;
else j = next[j];
}
}

int Kmp()
{
int i = 0;
int j = 0;
int ret = 0;
int tlen = strlen(text);
int wlen = strlen(word);
while (i < tlen)
{
if (-1 == j || text[i] == word[j])
{
++i;
++j;
if (j == wlen)
{
++ret;
j = next[j];    // 已经匹配成功,重新定位j指向word中的位置
}
}
else j = next[j];     // 失配时,重新定位j指向word中的位置
}
return ret;
}

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