题目描述:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
【分析】
例如:输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab";
第一步:翻转字符串“ab”,得到"ba";
第二步:翻转字符串"cdefg",得到"gfedc";
第三步:翻转字符串"bagfedc",得到"cdefgab";
三次翻转就完了。
class Solution {
public:
string LeftRotateString(string str, int n) {
string result = str;//复制str到result
int length = result.size();
if(length < 0)//鲁棒性
{
return " ";
}
if(0 <= n <= length)
{
int pFirstBegin = 0, pFirstEnd = n - 1;
int pSecondBegin = n, pSecondEnd = length - 1;
SwapString(result, pFirstBegin, pFirstEnd);
SwapString(result, pSecondBegin, pSecondEnd);
SwapString(result, pFirstBegin, pSecondEnd);
}
return result;
}
private:
void SwapString(string &str, int begin, int end)//翻转字符串
{
while(begin < end)
{
swap(str[begin++], str[end--]);//交换反转
}
}
};