编程之美 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值