0%

左旋转字符串

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

翻转3次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
void swap(string &text, const int a, const int b)
{
int x = a, y = b - 1;
while (x < y)
{
char temp = text[x];
text[x] = text[y];
text[y] = temp;
x++;
y--;
}
}
string LeftRotateString(string str, int n) {
const int length = str.length();
if (length <= 1)
{
return str;
}
n %= length;
if (n == 0)
{
return str;
}
swap(str, 0, n);
swap(str, n, length);
swap(str, 0, length);
return str;
}
};