字符串移位包含的问题

来源:互联网 发布:西瓜影音播放器 mac 编辑:程序博客网 时间:2024/05/22 09:02

问题:给定字符串s和t,判断是否字符串t能通过将s移位后的字符串所包含。

  1. 方法一
    最简单的方法就是将s进行循环移位,再判断移位后的字符串是否包含字符串t,代码如下:
#include <iostream>#include <string.h>#include <math.h>using namespace std;bool isSubstr(string s, string t){    for(int i = 0; i < s.length(); ++i){        //循环移位        char c = s[0];        for(int j = 0; j < s.length()-1; ++j){            s[j] = s[j+1];        }        s[s.length()-1] = c;        //判断t是否是s移位后的子串        string::size_type idx = s.find(t);        if(idx != string::npos){            cout << "true" << endl;            return true;        }    }    cout << "false" << endl;    return false;}int main(){    string s = "ABCD";    string t = "ACDB";    string ss = s+s;    isSubstr(s, t);    return 0;}

2.方法二
利用空间换时间,将两个字符串s拼接成一个,即ss,对s循环移位后的字符串都是ss的子串。若字符串t能通过对s循环移位得到,那么字符串t也是ss的子串。代码如下:

#include <iostream>#include <string.h>#include <math.h>using namespace std;bool isSubstr(string s, string t){    //拼接字符串s    string ss = s+s;    cout << ss << endl;    //判断t是否是ss的子串    string::size_type idx = ss.find(t);    if(idx != string::npos){        cout << "true" << endl;        return true;    }    else{        cout << "false" << endl;        return false;    }}int main(){    string s = "BACD";    string t = "ACDB";    isSubstr(s, t);    return 0;}
原创粉丝点击