LeetCode 796. 旋转字符串
作者:互联网
1. 题目
给定两个字符串, A 和 B。
A 的旋转操作就是将 A 最左边的字符移动到最右边。 例如, 若 A = ‘abcde’,在移动一次之后结果就是’bcdea’ 。如果在若干次旋转操作之后,A 能变成B,那么返回True。
示例 1:
输入: A = 'abcde', B = 'cdeab'
输出: true
示例 2:
输入: A = 'abcde', B = 'abced'
输出: false
注意:
A 和 B 长度不超过 100。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rotate-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
如果满足题意的话,A+A 中一定可以找到B
class Solution {
public:
bool rotateString(string A, string B) {
return A.size() == B.size() && (A + A).find(B) != string::npos;
}
};
or
class Solution {
public:
bool rotateString(string A, string B) {
if(A.size() != B.size())
{
return false;
}
if(A.size() <= 1)
{
return A==B;
}
int i = -1;
string roate;
while((i = A.find(B[0], i+1)) > 0)//A中能找到B的开头的位置
{
roate = A.substr(i) + A.substr(0, i);
if(roate == B)
return true;
}
return false;
}
};
or
class Solution {
int i, n;
char ch;
public:
bool rotateString(string A, string B) {
if(A.size() != B.size())
return false;
n = A.size();
if(n<=1)
return A==B;
int t = n;
while(t--)
{
movestr(A);
if(A==B)
return true;
}
return false;
}
void movestr(string &s)
{ //所有位置向右平移
ch = s[n-1];
i = n-1;
while(i-1>=0)
{
s[i] = s[i-1];
i--;
}
s[0] = ch;
}
};
0 ms 8.2 MB
标签:796,return,string,public,rotateString,字符串,false,LeetCode,size 来源: https://blog.csdn.net/qq_21201267/article/details/105775449