链接:
https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?
tpId=13&tqId=11196&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
描述:
示例:
代码:
方法一:
普通方法,一次移动一个,慢慢移动
class Solution {
public:
void LeftRotateStringOne(string& str){
char temp = str[0];
int i = 0;
for(;i<str.size()-1;i++)
{
str[i] = str[i+1];
}
str[i] = temp;
}
string LeftRotateString(string str, int n) {
if(n == 0 || str.empty())
return str;
n %= str.size();
while(n--)
{
LeftRotateStringOne(str);
}
return str;
}
};
方法二:
旋转
0到n旋转
0到end旋转
0到end旋转
class Solution {
public:
void ReverseString(string &str,int start,int end){
while(start<end){
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
string LeftRotateString(string str, int n)
{
if(str.empty() || n == 0) return str;
n%=str.size();
ReverseString(str,0,n-1);
ReverseString(str,n,str.size()-1);
ReverseString(str, 0, str.size()-1);
return str;
}
};
方法三:
截取运用substr函数
substr(开始的位置,需要多长);
class Solution {
public:
string LeftRotateString(string str, int n)
{
if(str.empty()|| n == 0) return str;
n%= str.size();
return str.substr(n)+str.substr(0,n);
}
};
方法四:
拼接:
创建一个字符串result是两个str
然后返回result的(n到n+str.size())之间的数据
class Solution {
public:
string LeftRotateString(string str, int n)
{
if(str.empty() || n == 0) return str;
n %= str.size();
string result = str+str;
return result.substr(n,str.size());
}
};