题目描述: 给定两个字符串s1, s2 , 要求判定s2是否能够被s1做循环移位得到的字符串包含
解题思路: 复制一遍s1重新接到s1后面 , 再查询, O(nk)的时间复杂度, 还有一种不需要申请过多新空间的方法
代码:
#include <iostream> #include <queue> #include <string> #include <vector> #include <algorithm> #include <list> #include <iterator> #include <cmath> #include <cstring> #include <forward_list> using namespace std; int main() { string s1,s2; cin >> s1 >> s2; s1 += s1; if(find(s1,s2)!=-1) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
#include <iostream> #include <queue> #include <string> #include <vector> #include <algorithm> #include <list> #include <iterator> #include <cmath> #include <cstring> #include <forward_list> using namespace std; int my_find(string s1, string s2) { int len1 = (int)s1.length(); int len2 = (int)s2.length(); int found = 0; int cnt = 0; while(cnt < 2*len1) { int pos1 = cnt%len1; int pos2 = 0; if(s1[pos1] == s2[pos2]) { int i = 0; for(i = 0; i < len2; i++) { if(s1[(pos1+i)%len1] != s2[pos2+i]) break; } if(i == len2) { found = 1; break; } } cnt++; } if(found) return 1; else return 0; } int main() { string s1,s2; cin >> s1 >> s2; if(my_find(s1,s2)) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
思考: 都是脑洞题, 锻炼锻炼自己的思维也不错, 然后下面夯实自己的数据结构基础