您的位置:首页 > 编程语言

《编程之美》 - 3.1 字符串移位包含的问题( 不用strstr()的解法 )

2013-09-29 23:37 330 查看
/*  题目:
给定两个字符串s1和s2,要求判定s2是否能被s1做循环移位得到的字符串所包含
例如,给定s1 = AABCD, s2 = CDAA,返回true,给定s1 = ABCD, s2 = ACBD,返回false
*/

#include <iostream>
#include <string>
using namespace std;
bool isrotate(string s1,string s2);
int main()
{
string s1,s2;
cout << "输入s1:";
cin >> s1;
cout << "输入s2:";
cin >> s2 ;
if (isrotate(s1,s2))
cout << "Yes"<< endl;
else
cout << "No" << endl;
}
bool isrotate(string s1,string s2)
{

for(int i = 0; i < s1.length();i++)
{

//首字符不符合,跳过
if (s1[i] != s2[0])
continue;
else
{
int j = i + 1;
int k = 1;
while(1)
{
if(j == s1.length())
j = 0;

if(k == s2.length())
return true;

if(s1[j] != s2[k])
break;
else
{
j++;
k++;
}
}
}

}
return false;
}


--------------------------------------------------------------------------------------------------------------------------------------------------------------

/* 《编程之美》 中的解法

假设

s1[] = "ABCD"
s2[] = "DA"

将s1扩充

ABCD -> ABCDA -> ABCDAB -> ABCDABC -> ABCDABCD

则 s2 含于 ABCDABCD

提高空间复杂度来换取时间复杂度的降低
*/


/* 函数概述

包含文件:string.h
函数名: strstr
函数原型:extern char *strstr(char *str1, char *str2);
功能:从字符串str1中查找是否有字符串str2,如果有,从str1中的str2位置起,返回str1中str2起始位置的指针,如果没有,返回null。
返回值:返回该位置的指针,如找不到,返回空指针。
例子:

char str[]="1234 xyz";
char* str1=strstr(str,"34");
cout<<str1<<endl;

显示:    34 xyz

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: