题目:左旋字符串:例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”
思路:
先分为两个部分,两个部分分别翻转,然后整体翻转。注意要用引用
class Solution {
public:
string LeftRotateString(string str, int n) {
int length=str.size();
if(length==0|n==0){
return str;
}
Reverse(str,0,n-1);
Reverse(str,n,length-1);
Reverse(str,0,length-1);
return str;
}
void Reverse(string &str,int low,int high){
while(low<high){
int tmp=str[low];
str[low]=str[high];
str[high]=tmp;
low++;
high--;
}
}
};