《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\".\n", s1);
51     }
52     
53     return 0;
54 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3606685.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值