编程之美 3.1 字符串移位包含问题
生活随笔
收集整理的這篇文章主要介紹了
编程之美 3.1 字符串移位包含问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述: 給定兩個字符串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; } View Code #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; } View Code思考: 都是腦洞題, 鍛煉鍛煉自己的思維也不錯, 然后下面夯實自己的數據結構基礎
轉載于:https://www.cnblogs.com/FriskyPuppy/p/8012446.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的编程之美 3.1 字符串移位包含问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java项目实现流水号自动增长
- 下一篇: Python 学习笔记 -- 序列的基本