CCI_Q1.8

本文参考该作者文章当作编程笔记:

作者:Hawstein
出处:http://hawstein.com/posts/ctci-solutions-contents.html

一.

Q:假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。

思路:将字符串s1+s1,再判断s2是不是s1+s1的子串,如果是,s2就是s1的旋转字符串。eg:s1:abcd,  s2:dabc,  s1+s1:abcdabcd.

Talk is cheap,Show me code:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #define N 5
 5 int isSubstring (char s1[],char s2[])
 6 {
 7     char *sub=strstr(s1,s2);
 8     if(sub==NULL)
 9         return 0;
10     return 1;
11 }
12 int isRotation(char s1[],char s2[])
13 {
14     strcat(s1,s1);
15     if(isSubstring(s1,s2)==1)
16         return 1;
17     return 0;
18 }
19 int main()
20 {
21     char s1[N+N]="abcd";
22     char s2[N]="dabc";
23     if(isRotation(s1,s2))
24         printf("yes");
25     else
26         printf("no");
27     return 0;
28 }
原文地址:https://www.cnblogs.com/jhooon/p/3577681.html