题目:
思路:这道题目关键在思路吧,没什么想法的话,这里先给一个提示:string str = A + A,先思考一下然后再看答案代码。
下面贴代码,一些解释写在代码注释里
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
bool rotateString(string A, string B) {
if(A.length() != B.length())
return false;
else{
string str = A + A;
int len = B.length();
for(int i = 0; i < len; i++){
int j = 0;
if(str[i] == B[j]){ //首先这里找到B的第一个字母在A中的位置
while(j < len){
if(str[i+j] == B[j])
j++; //这里是要判断是否B完全在A+A中
else break;//在else中,要及时跳出循环,避免死循环
}
if(j == len) return true;//这里用来判断,跳出循环是因为j加到了B.length()还是因为str[i+j] != B[j]
}
}
return false;
}
}
};
int main(){
Solution so;
string A = "abcde";
string B = "abced";
cout << so.rotateString(A,B) <<endl;
system ("pause");
return 0;
}
还有一种解法是利用基本函数substr,
这里对substr做一个说明:
例如:
string s = "asdfghjkl ";
substr sub1 = s(1); //表示从下标1开始至结束 即sub1 = "sdfghjkl";
substr sub2 = s(1,4); //表示从下标1开始,截取4个字符,即sub2 = "sdfg";
substr sub3 = s(7,5); //表示从下标8开始截取5个字符,但剩余字符少于5个,则截取至结束,即sub3 = "kl";
class Solution {
public:
bool rotateString(string A, string B) {
if(A.length() != B.length())
return false;
else{
int len = A.length();
for(int i = 0; i < len; i++)
if(A.substr(i,len)+A.substr(0,i) == B)
return true;
return false;
}
}
};