zoukankan      html  css  js  c++  java
  • 编程之美 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

      思考: 都是脑洞题, 锻炼锻炼自己的思维也不错, 然后下面夯实自己的数据结构基础

  • 相关阅读:
    docker.service启动失败:Unit not found
    本地测试环境搭建
    2016 年总结
    node-http-proxy修改响应结果
    JavaScript那些事儿(01): 对象
    Javascript正则表达式
    addEventListener之handleEvent
    《CSS那些事儿》读书笔记
    《编写高质量代码--Web前端开发修炼之道》读书笔记
    Javascript闭包简单理解
  • 原文地址:https://www.cnblogs.com/FriskyPuppy/p/8012446.html
Copyright © 2011-2022 走看看