《Cracking the Coding Interview》——第1章:数组和字符串——题目8

2014-03-18 02:12

题目:判断一个字符串是否由另一个字符串循环移位而成。

解法:首先长度必须相等。然后将第一个串连拼两次,判断第二个串是否在这个连接串中。

代码:

 1 // 1.8 Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     bool isStringRotation(char *s1, char *s2) {
 9         if (s1 == nullptr || s2 == nullptr) {
10             return false;
11         }
12         
13         int len1, len2;
14         
15         len1 = strlen(s1);
16         len2 = strlen(s2);
17         if (len1 != len2) {
18             return false;
19         }
20         
21         const int MAXLEN = 1005;
22         static char tmp[MAXLEN];
23         
24         tmp[0] = 0;
25         strcat(tmp, s1);
26         strcat(tmp, s1);
27         return strstr(tmp, s2) != nullptr;
28     }
29 private:
30     bool isSubstring(char *haystack, char *needle) {
31         if (haystack == nullptr || needle == nullptr) {
32             return false;
33         }
34         
35         return strstr(haystack, needle) != nullptr;
36     }
37 };
38 
39 int main()
40 {
41     char s1[1005];
42     char s2[1005];
43     Solution sol;
44     
45     while (scanf("%s%s", s1, s2) == 2) {
46         printf(""%s" is ", s2);
47         if (!sol.isStringRotation(s1, s2)) {
48             printf("not ");
49         }
50         printf("a rotation of "%s".
", s1);
51     }
52     
53     return 0;
54 }