(1.5.2.12)字符串循环移位 编程之美3.1

来源:互联网 发布:上海大型网络工程公司 编辑:程序博客网 时间:2024/06/03 00:00

http://blog.sina.com.cn/s/blog_7d6898410101a66e.html

http://www.cnblogs.com/kevinLee-xjtu/archive/2011/12/14/2299087.html


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


思路1:找出所有循环移位,逐个进行字符串匹配。n*字符串匹配的复杂度。kmp可以做到线性,因此总的复杂度为n^2.

思路2:s1复制一下,变成s1s1,如s1=ABCD,变成ABCDABCD,用它进行匹配。那样就是2n的字符串匹配。不过要浪费n的空间。

思路3:还是按原来一样做字符串匹配,只不过匹配串的尾端允许超出源字符串范围(开头不能超过),用%对下标求余。空间O(1),时间O(n)。

思路3代码:

[cpp] view plaincopy
  1. #include<stdio.h>  
  2.   
  3. // 循环移位字符串的包含问题,编程之美3.1  
  4. //  
  5. int findstr(const char*s1, const char *s2)  
  6. {  
  7.     if(s1==NULL || s2 == NULL)  
  8.         return -1;  
  9.     int i=0,j=0;  
  10.     int m1=0,m2=0;  
  11.     const char *p;  
  12.     p=s1;  
  13.     while(*p != '\0')  
  14.     {  
  15.         m1++;  
  16.         p++;  
  17.     }  
  18.     p=s2;  
  19.     while(*p != '\0')  
  20.     {  
  21.         m2++;  
  22.         p++;  
  23.     }  
  24.     while(i < m1 && j < m2)  
  25.     {  
  26.         if(s1[ (i+j)%m1 ] == s2[j])  
  27.             j++;  
  28.         else  
  29.         {  
  30.             i++;  
  31.             j = 0;  
  32.         }  
  33.     }  
  34.     if(j == m2)  
  35.         return 1;  
  36.     return 0;  
  37.       
  38. }  
  39. int main()  
  40. {  
  41.     char s1[] = "abcdef";  
  42.     char s2[] = "efab";  
  43.     char s3[] = "efb";  
  44.     printf("is %s in %s ? %d\n", s2, s1, findstr(s1,s2) );  
  45.     printf("is %s in %s ? %d\n", s3, s1, findstr(s1,s3) );  
  46.     return 0;  
  47. }  

输出:

is efab in abcdef ? 1is efb in abcdef ? 0
0 0
原创粉丝点击