判断两个字符串是否互为旋转词
题目描述
如果一个字符串为str,把字符串的前面任意部分挪到后面形成的字符串交str的旋转词。比如str=“12345”,str的旋转串有“12345”、“45123”等等。给定两个字符串,判断是否为旋转词。
输入描述:
输出包含三行,第一个两个整数n和m ( 1 ≤ n , m ≤ 1 0 5 ) (1 \leq n,m \leq10^5) (1≤n,m≤105),分别表示两个字符串的长度。第二行和第三行各输入一个字符串。
输出描述:
如果两个字符串互为旋转词请输出“YES”,否则输出“NO”。
示例1
输入
4 4
abcd
cdab
输出
YES
示例2
输入
2 3
aa
aaa
输出
NO
备注:
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)。
题解:
- 若两个字符串长度不相等,则必然不互为旋转词;
- 将一个字符串复制一份拼接起来,若另一个在其中出现,则必定互为旋转词(很容易想通为什么)。
代码:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
string s1, s2;
int n, m;
cin >> n >> m;
if (n != m) return 0 * puts("NO");
cin >> s1 >> s2;
s2 += s2;
if (s2.find(s1) != -1) puts("YES");
else puts("NO")
return 0;
}