题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
思路:
例如:输入字符串"afkh"和数字2,该函数将返回左旋转2位得到的结果"khaf";
第一步:翻转字符串“af”,得到"fa";
第二步:翻转字符串"kh",得到"hk";
第三步:翻转字符串"fahk",得到"khaf";
或者:
第一步:翻转整个字符串"afkh",得到"hkfa"
第二步:翻转字符串“hk”,得到"kh"
第三步:翻转字符串"fa",得到"af"
class Solution {
public:
string LeftRotateString(string str, int n) {
string result = str;
int length = result.size();
if(length < 0){
return NULL;
}
if(0 <= n <= length){
int pFirstBegin = 0, pFirstEnd = n - 1;
int pSecondBegin = n, pSecondEnd = length - 1;
ReverseString(result, pFirstBegin, pFirstEnd);
ReverseString(result, pSecondBegin, pSecondEnd);
ReverseString(result, pFirstBegin, pSecondEnd);
}
return result;
}
private:
void ReverseString(string &str, int begin, int end){
while(begin < end){
swap(str[begin++], str[end--]);
}
}
};