【Cracking the coding interview】Q1.8(旋转字符串)
2013-12-23 21:52
387 查看
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”).
假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。
思路: erbottlewat一定是waterbottle+waterbottle的子串
is a rotation of “erbottlewat”).
假设你有一个isSubstring函数,可以检测一个字符串是否是另一个字符串的子串。 给出字符串s1和s2,只使用一次isSubstring就能判断s2是否是s1的旋转字符串, 请写出代码。旋转字符串:"waterbottle"是"erbottlewat"的旋转字符串。
思路: erbottlewat一定是waterbottle+waterbottle的子串
#include <iostream> #include <string> using namespace std; bool isSubstring(string s1, string s2){ if(s1.find(s2) != string::npos) return true; else return false; } bool isRotation(string s1, string s2){ if(s1.length() != s2.length() || s1.length()<=0) return false; return isSubstring(s1+s1, s2); } int main(){ string s1 = "apple"; string s2 = "pleap"; cout<<isRotation(s1, s2)<<endl; cout<<string::npos<<endl; system("pause"); return 0; }
相关文章推荐
- 【Cracking the coding interview】Q1.7(矩阵置0)
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目1
- Cracking the coding interview--Q1
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 【Cracking the coding interview】Q1.1(字符唯一)
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目4
- Cracking the coding interview--Q1.1(python的位操作)
- 【Cracking the coding interview】Q1.2(反转字符串)
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目5
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- 【Cracking the coding interview】Q1.4(变位词)
- 【Cracking the coding interview】Q1.5(替换字符串)
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q19.6
- Cracking the coding interview--Q2.2
- Cracking The Coding Interview 4.4