《Cracking the Coding Interview》——第1章:数组和字符串——题目8
2014-03-18 02:15
543 查看
2014-03-18 02:12
题目:判断一个字符串是否由另一个字符串循环移位而成。
解法:首先长度必须相等。然后将第一个串连拼两次,判断第二个串是否在这个连接串中。
代码:
题目:判断一个字符串是否由另一个字符串循环移位而成。
解法:首先长度必须相等。然后将第一个串连拼两次,判断第二个串是否在这个连接串中。
代码:
// 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”). #include <cstdio> #include <cstring> using namespace std; class Solution { public: bool isStringRotation(char *s1, char *s2) { if (s1 == nullptr || s2 == nullptr) { return false; } int len1, len2; len1 = strlen(s1); len2 = strlen(s2); if (len1 != len2) { return false; } const int MAXLEN = 1005; static char tmp[MAXLEN]; tmp[0] = 0; strcat(tmp, s1); strcat(tmp, s1); return strstr(tmp, s2) != nullptr; } private: bool isSubstring(char *haystack, char *needle) { if (haystack == nullptr || needle == nullptr) { return false; } return strstr(haystack, needle) != nullptr; } }; int main() { char s1[1005]; char s2[1005]; Solution sol; while (scanf("%s%s", s1, s2) == 2) { printf("\"%s\" is ", s2); if (!sol.isStringRotation(s1, s2)) { printf("not "); } printf("a rotation of \"%s\".\n", s1); } return 0; }
相关文章推荐
- 联想A658t特殊指令集
- 联想A658t特殊指令集
- 程序员遇到bug时常见的30种反应
- UVa 10013 - Super long sums
- mysql笔记-- mysql命令札记2
- 火眼金睛 教你看懂电源内部用料
- hrbust 1632 最大的最小公倍数
- hrbust 1632 最大的最小公倍数
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 12事件
- 《Cracking the Coding Interview》——第3章:栈和队列——题目5
- 配置apache + tomcat 绑定泛域名
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 小白鼠与毒药解题过程分析
- 中文乱码解决方案
- Cocos2d-x适配解决方案及原理分析
- tomcat的URIEncoding的作用(转)
- 3.17数组知识补课
- C#编程语言
- 3.14笔记