您的位置:首页 > 其它

[hdu][2203][亲和串]

2012-02-15 20:54 246 查看
题目:http://acm.hdu.edu.cn/showproblem.php?pid=2203

给定两个字符串s1和s2,如果能通过s1循环移位,使s2包含在s1中,那么我们就说s2 是s1的亲和串。

View Code

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

using namespace std;

const int MAXV = 200000+10;

void kmp(char in[], int len, int path[])
{
int i, j = -1; path[0] = -1;
for (i = 1; i < len; i++)
{
while (j >= 0 && in[j+1] != in[i]) j = path[j];
if (in[j+1] == in[i]) j++;
path[i] = j;
}
}

char s1[MAXV], s2[MAXV];
int p[MAXV];

int main()
{
int l1, l2, ok;
while (scanf("%s%s", s1, s2) != EOF)
{
l1 = strlen(s1); l2 = strlen(s2);
ok = 0;
if (l1 < l2)
{
printf("no\n");
continue;
}
kmp(s2, l2, p);
int i, j=-1;
for (i = l1; i < l1+l2; i++) s1[i] = s1[i-l1];
s1[i] = '\0';
for (i = 0; i < l1+l2 && !ok; i++)
{
while (j > -1 && s1[i] != s2[j+1]) j = p[j];
if (s2[j+1] == s1[i]) j++;
if (j == l2-1)
{
printf("yes\n");
ok = 1;
}
}
if (!ok) printf("no\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: