CCI习题1-8:Is Rotation

By | 2012 年 11 月 13 日

先判断长度是否相等;
然后将第一个字符串s0和自己连接变成s00,调用isSubstring,判断s1是否是s00的一个子串就可以了。



题目
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”).



代码

<

pre>

//
// main.cpp
// CCI.1.8.IsRotateString
//
// Created by Qiu Xiangyu on 12-11-13.
// Copyright (c) 2012年 Qiu Xiangyu. All rights reserved.
//

include

include

using namespace std;

bool isRotation(string &str0, string &str1) {
if (str0.size() != str1.size()) {
return false;
}
string str00 = str0 + str0;
size_t loc = str00.find(str1);
cout<<loc<<endl;
return loc < str00.size();
}

int main(int argc, const char * argv[])
{
// insert code here…
cout << “Input Str0 below:\n”;
string str0;
cin>>str0;
cout<<“Input Str0:”<<str0<<endl<<“Input Str1 below:”<<endl;
string str1;
cin>>str1;
cout<<“Input Str1:”<<str1<<endl;

//process
bool isRotate = isRotation(str0,str1);
cout<<"Result : "<<isRotate<<endl;

return 0;

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注