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

探讨如何判断一个字符串s2是否能通过另一个字符串s1的循环移位得到,提出两种解法:直接循环移位判断和利用s1自身拼接判断。降低时间复杂度,提高空间效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定两个字符串s1和s2,要求判定s2是否能够被s1做循环移位得到的字符串包含。

解法一:直接对s1进行循环移位,再进行字符串包含判断。代码如下:

 #include<string.h>  //C风格形式
 using namespace std;
 
 void main()
 { char src[] ="AABBCD";
   char des[] ="CDAA";
 
   int len=strlen(src);
   for(int i=0;i<len;i++)
   {  
     char tempchar=src[0];
     for(int j=0;j<len-1;j++)
        src[j]=src[j+1];
     src[len-1]=tempchar;
     if(strstr(src,des)==0)  
 //原型:extern char *strstr(char *haystack,char *needle);用法:#include<strng.h>
     {  cout<<"包含"<<endl;
        return ;
    }
   }
  // return false;
  cout<<"不包含"<<endl; 
 }

解法二:
分解s1的循环移位得到:
AABCD,ABCDA,BCDAA,CDAAB,.....
如果我们将前面移走的字符串保留下来,则有:
AABCD,AABCDA,AABCDAA,AABCDAAB,AABCDAABC,AABCDAABCD

这里,我们可以发现,实际对s1的循环移位得到的字符串实际为s1s1。
那么我们判断s2是否可以通过s1循环移位得到包含,则只需要判断s1s1中是否含有s2即可以。
用提高空间复杂度来换取时间复杂度的减低的目的。代码如下:

 #include<iostream>
 #include<string>
 
 using namespace std;
 
 bool rotstr(string src,string des)
 {
     string tmp = src;
     src=src+tmp;
     if(strstr(src.c_str(),des.c_str())==NULL)
     {
         return false;
     }
     return true;
 }
 
 int main()
 {
     string src="AABBCD";
     string des="DAAB";
     if(rotstr(src,des))
         cout<<"the string des is included in the rotated string of src "<<endl;
     else
         cout<<"the string des is not included in the rotated string of src "<<endl;
     return 0;
 }



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值