标签:string NO int Next 循环 YES 移位 Cycle
Description
Cycle shifting refers to following operation on the sting. Moving first letter to the end and keeping rest part of the string. For example, apply cycle shifting on ABCD will generate BCDA. Given any two strings, to judge if arbitrary times of cycle shifting on one string can generate the other one.
Input
There m lines in the input, while each one consists of two strings separated by space. Each string only contains uppercase letter 'A'~'Z'.
Output
For each line in input, output YES in case one string can be transformed into the other by cycle shifting, otherwise output NO.
Example
Input
AACD CDAA
ABCDEFG EFGABCD
ABCD ACBD
ABCDEFEG ABCDEE
Output
YES
YES
NO
NO
Restrictions
0 <= m <= 5000
1 <= |S1|, |S2| <= 10^5
Time: 2 sec
Memory: 256 MB
描述
所谓循环移位是指。一个字符串的首字母移到末尾, 其他字符的次序保持不变。比如ABCD经过一次循环移位后变成BCDA
给定两个字符串,判断它们是不是可以通过若干次循环移位得到彼此
输入
由m行组成,每行包含两个由大写字母'A'~'Z'组成的字符串,中间由空格隔开
输出
对于每行输入,输出这两个字符串是否可以通过循环移位得到彼此:YES表示是,NO表示否
样例
见英文题面
限制
0 ≤ m ≤ 5000
1 ≤ |S1|, |S2| ≤ 10^5
时间:2 sec
内存:256 MB
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #define N 200005 5 using namespace std; 6 7 void getNext(int Next[],char b[],int len) 8 { 9 memset(Next,0,sizeof(Next)); 10 Next[0]=-1; 11 for(int i=0,j=-1;i<len;) 12 if(j==-1||b[i]==b[j]) 13 Next[++i]=++j; 14 else 15 j=Next[j]; 16 } 17 int kmp(char a[],char b[],int Next[]) 18 { 19 int n,len; 20 n=strlen(a); 21 len=strlen(b); 22 getNext(Next,b,len); 23 24 for(int i=0,j=0;i<n;) 25 { 26 if(j==-1||a[i]==b[j])i++,j++; 27 else 28 j=Next[j]; 29 if(j>=len) 30 return 1; 31 } 32 return 0; 33 } 34 35 int Next[N]; 36 char a[N],b[N]; 37 char c[N*2]; 38 39 int main() 40 { 41 while(scanf("%s %s",a,b)==2) 42 { 43 strcpy(c,a); 44 strcat(c,a); 45 46 if(strlen(a)==strlen(b)&&kmp(c,b,Next))printf("YES\n"); 47 else 48 printf("NO\n"); 49 } 50 return 0; 51 }
标签:string,NO,int,Next,循环,YES,移位,Cycle 来源: https://www.cnblogs.com/sylvia1111/p/15613049.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。