Similar Word | ||
| ||
description | ||
It was a crummy day for Lur. He failed to pass to the CET-6 (College English Test Band-6). Looking back on how it was in last year gone by, he gradually noticed he had fled too many English Lessons. But he determines to memorize words on his bed ,not in the classroom. You know, it is not that easy to pass the test mainly because the large amount of born words.
Lur is intelligent on games , never English. He cann't learn the similar words by heart. He
always choose to select a word to learn from the similar words . For him, two words are similar if and only if one word can equal to the other by multiple cyclic shift(at least 1). For example, "car" and "arc" are similar words, while "car" and "rca" are also similar words . To save more time to play games,
Lur want to know wether two words are similar words faster, he asks you to write a program to tell him ,can you help him ?
| ||
input | ||
There are multiple test cases. Each case contains two lines. Each line contains a word,
W. You can assume that length(W)<=10^5 . Ended by EOF.
| ||
output | ||
Output “yes” in a single line if two words are similar,otherwise you should output “no” in a single line.
| ||
sample_input | ||
car
arc
car
cra
car
car
| ||
sample_output | ||
yes
no
no
| ||
hint | ||
| ||
source |
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int mm=1e5+9;
char s[mm],t[mm+mm];
int nex[mm],ls,lt;
void get(char*s,int*nex)
{
memset(nex,0,sizeof(nex));
nex[0]=-1;
int x=-1,y=0;
while(y<ls)
{
if(x==-1||s[x]==s[y])
{
nex[++y]=++x;
}
else x=nex[x];
}
}
bool kmp(char*s,char*t)
{ get(s,nex);
int x=0,y=0;
while(x<ls&&y<lt)
{
if(x==-1||s[x]==t[y])++x,++y;
else x=nex[x];
}
return x==ls&&x^y;
}
int main()
{
while(~scanf("%s%s",s,t))
{
ls=strlen(s);
lt=strlen(t);
if(ls^lt){printf("no\n");continue;}
for(int i=0;i<ls;++i,++lt)
t[lt]=t[lt-ls];
t[lt]='\0';
///cout<<t<<endl;
printf("%s\n",kmp(s,t)?"yes":"no");
}
}
本文介绍了一个算法问题,即如何快速判断两个单词是否为相似单词。相似单词定义为一个单词可以通过多次循环移位变为另一个单词。文章提供了一段C++代码实现,通过KMP算法来解决该问题,并给出了一些示例输入输出。

1263

被折叠的 条评论
为什么被折叠?



