題目
【彙編語言中有一種移位指令叫做循環左移(ROL),現在有個簡單的任務,就是用字符串模擬這個指令的運算結果。對於一個給定的字符序列S,請你把其循環左移K位後的序列輸出。例如,字符序列S=”abcXYZdef”,要求輸出循環左移3位後的結果,即“XYZdefabc”】
1、分析
- 對於字符串的左移,可以看成字符串的多次翻轉的結果。如題中的字符串左移3位,可以先將字符串分成兩部分: abcXYZdef 。先對前一部分進行翻轉爲cba,再對後一部分進行翻轉爲 fedZYX。最後再整體的對翻轉後的字符串(cbafedZYX)翻轉一次,即爲所求的結果:XYZdefabc
2、代碼
class Solution {
public:
string LeftRotateString(string str, int n) {
int len=str.length();
// 注意len<0的情況,不能有等號
if(len<0)
return NULL;
if(len>=0 && n>=0 && n<=len)
{
int firstStart=0;
int firstEnd=n-1;
int secondStart=n;
int secondEnd=len-1;
ReverseStr(str,firstStart,firstEnd);
ReverseStr(str,secondStart,secondEnd);
ReverseStr(str,firstStart,secondEnd);
}
return str;
}
void ReverseStr(string &str,int start, int end)
{
while(start<end)
{
swap(str[start++],str[end--]);
}
}
};