题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
解题思路:本题思路借鉴于翻转单词顺序题目
例如abcdefg 和数字2 可以看做翻转ab 和 cdefg
先翻转ab cdefg得到 bagfedc 然后翻转整个字符串得到cdefgab
1 class Solution { 2 public: 3 void Reverse(char *pStart, char *pEnd) 4 { 5 if(pStart == NULL || pEnd == NULL) 6 return; 7 while(pStart < pEnd) 8 { 9 char tmp = *pStart; 10 *pStart = *pEnd; 11 *pEnd = tmp; 12 pStart++; 13 pEnd--; 14 } 15 } 16 string LeftRotateString(string str, int n) { 17 if(!str.empty()) 18 { 19 int length = str.size(); 20 if(length > 0 && n>0 && n < length) 21 { 22 char *pFirstStart = &str[0]; 23 char *pFirstEnd = &str[n-1]; 24 char *pSecondStart = &str[n]; 25 char *pSecondEnd = &str[length-1]; 26 //翻转前n个 27 Reverse(pFirstStart,pFirstEnd); 28 //翻转第n+1个到最后 29 Reverse(pSecondStart,pSecondEnd); 30 //翻转整个字符串 31 Reverse(pFirstStart,pSecondEnd); 32 } 33 } 34 return str; 35 } 36 };