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代码:
- #include<stdio.h>
- // 循环移位字符串的包含问题,编程之美3.1
- //
- int findstr(const char*s1, const char *s2)
- {
- if(s1==NULL || s2 == NULL)
- return -1;
- int i=0,j=0;
- int m1=0,m2=0;
- const char *p;
- p=s1;
- while(*p != '\0')
- {
- m1++;
- p++;
- }
- p=s2;
- while(*p != '\0')
- {
- m2++;
- p++;
- }
- while(i < m1 && j < m2)
- {
- if(s1[ (i+j)%m1 ] == s2[j])
- j++;
- else
- {
- i++;
- j = 0;
- }
- }
- if(j == m2)
- return 1;
- return 0;
- }
- int main()
- {
- char s1[] = "abcdef";
- char s2[] = "efab";
- char s3[] = "efb";
- printf("is %s in %s ? %d\n", s2, s1, findstr(s1,s2) );
- printf("is %s in %s ? %d\n", s3, s1, findstr(s1,s3) );
- return 0;
- }
输出:
is efab in abcdef ? 1 is efb in abcdef ? 0