1,题目要求
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = ‘abcde’, then it will be ‘bcdea’ after one shift on A. Return True if and only if A can become B after some number of shifts on A.
即给定两个字符串,看二者是否是循环相同的。
2,题目思路
一开始想到直接按位进行判断,但是这样非常的麻烦。因为在字符串很长是,很难找到二者开始相同的起始点。因此需要利用别的方法来做。
首先,对两个字符串的长度进行比较,如果长度一样,才会继续进行判断。
其次,用到了c++中查找一个字符串是否有另一个字符串为子串的一种方法:
此处需要用到string库中的find函数与npos参数。
首先,对于string::npos参数,这是一个常数,用来表示不存在的位置。
对于find函数,find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos。
3,程序源码:
class Solution {
public:
bool rotateString(string A, string B) {
return (A.length() == B.length()) && ((A + A).find(B) != string::npos);
}
};