题目描述
给定两个字符串 s 与 p,请判定 �p 是否是 �s 的循环节。所谓循环节就是将 p 复制若干遍拼接在一起后,恰好等于 s。
输入格式
- 第一行:单个字符串 s;
- 第二行:单个字符串 p
输出格式
- 如果 p 是 s 的循环节,输出
Yes
,否则输出No
。
数据范围
设 s 与 p 的长度分别为 n 与 m,则
- 对于 50% 的数据,1≤n,m≤1000;
- 对于 100% 的数据,1≤n,m≤1,000,000;
样例数据
输入:
xyxy
xy
输出:
Yes
输入:
1428571428571428571428
142857
输出:
No
题解
本题关键点:2个判断:如果s字符串的长度不是p字符串长度的n倍,则肯定不是;如果p字符串在p字符串中的个数不是n倍,也不是。代码如下。
#include <iostream>
#include <string>
using namespace std;
int main(){
string s,p;
long long n,m;
int times,count,index;
cin>>s>>p;
n=s.length();
m=p.length();
times=0;
count=0;
index=0;
if(n%m==0){
times=n/m;
while( (index=s.find(p,index)) < n && index>=0){
count++;
index++;
}
if(times==count){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}else{
cout<<"No"<<endl;
}
return 0;
}