编程之美3.1 字符串移位包含问题

给定两个字符串s1和s2,要求判断s2是否能够被s1做循环移位得到的字符串包含。例如,给定s1=AABCD和s2=CDAA,返回true;给定s1=ABCD,s2=ACBD,返回false。

解法一:穷举法

int Contain1( char*str1, constchar*str2 )
{
   
int len = strlen(str1);
   
for (int i =0; i < len; i++)
    {
       
char temchar = str1[0];
       
for (int j =0;j < len-1; j++)
        {
str1[j]
= str1[j+1];
        }
        str1[len
-1] = temchar;
       
if (strstr(str1, str2) )
        {
           
return1;
        }
    }
   
return0;
}
解法二:空间换取时间复杂度法

 

bool contain2(char * s1, char * s2)

 

{

 

    assert(s1);

 

    assert(s2);

 

    char * temp = new char[strlen(s1)*2 + 1];

 

    strcpy(temp,s1);

 

    strcat(temp,s1);

 

    if(strstr(temp, s2) != NULL)

 

        return true;

 

    else

 

        return false;

 

    delete[] temp;

 

}

主函数:

#include "stdafx.h"
#include
<iostream>
usingnamespace std;
//穷举法
int contain1(char*str1, constchar*str2);
//空间换取时间法
int contain2(char*str1, constchar*str2);
int _tmain(int argc, _TCHAR* argv[])
{
   
char str1[] ="AABBCD";
   
char str2[] ="CDAA";
   
int ret1 = IfRotateContain1(str1, str2);
   
int ret2 = IfRotateContain2(str1, str2);
    cout
<< ret1 << endl;
    cout
<< ret2 << endl;
   
return0;
}

posted on 2012-08-13 17:34  yousir  阅读(194)  评论(0)    收藏  举报

导航