随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(375)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示