程式設計之美:3.1 字串移位包含的問題
阿新 • • 發佈:2019-01-31
給一個S1=”AABCD”,判斷S2是否能通過S1移位得到,例如S2=“CDAA”,應該返回true。
#include<iostream>
#include<string>
using namespace std;
/*
該函式主要是遍歷的方法,將所有情況都測試一遍,效率較低
時間複雜度為O(n2)
*/
void function1(string src, string des)
{
int len = src.length();
//src += "123";
//cout << src << endl;
for (int i = 0; i < len; i++)
{
char temp = src[0];
for (int j = 0; j < len - 1; j++){
src[j] = src[j + 1];
}
src[len -1] = temp;
//判斷是否包含該字串
if (src.find(des) != string::npos){
cout << "true" << endl;
return ;
}
}
}
/*
This function is based on the theory that if s2 can roll from
s1, then s2 must be a substr of s1s1.
*/
void function2(string src, string des)
{
src += src;
cout << src << endl;
if (src.find(des) != string::npos){
cout << "true" << endl;
return ;
}
return;
}
int main()
{
string src;
string des;
while (cin >> src){
cin >> des;
//在function1中對src 和 des的改變將不會影響主程式的src和des,這和java有一定的區別
//function1(src, des);
//cout << src << endl;
function2(src, des);
}
}
擴充套件問題: 如果不能申請過多新的空間,怎麼解決這個問題。(待完善)