-
Notifications
You must be signed in to change notification settings - Fork 1
/
45_左旋转字符串
81 lines (75 loc) · 1.48 KB
/
45_左旋转字符串
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>
using namespace std;
/*
题目描述L
汇编语言中有一种移位指令叫做循环左移(ROL)。
现在有个简单的任务,就是用字符串模拟这个指令的运算结果。
对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。
例如,字符序列S="abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
*/
class Solution
{
public:
string LeftRotateString(string str, int n)
{
int size = str.size();
if (size < 2)
{
return str;
}
int step = n % size;
if (size == n)
{
return str;
}
if (step < ( size / 2 + 1) ) //左移step
{
char *tmp = new char[step];
for (int i = 0; i < size - step; ++i)
{
if (i < step)
{
tmp[i] = str[i];
}
str[i] = str[i + step];
}
for (int i = size - step; i < size; ++i)
{
str[i] = tmp[i - size + step];
}
}
else //右移(size - step)位
{
step = size - step;
char *tmp = new char[step];
for (int i = size - 1; i >= step; --i)
{
if (i >= size - step)
{
tmp[size - 1 - i] = str[i];
}
str[i] = str[i - step];
}
for (int i = 0; i < step; ++i)
{
str[i] = tmp[step - i - 1];
}
}
return str;
}
};
void Test()
{
string str1 = "";
for (int i = 0; i < 12; ++i)
{
string ret = Solution().LeftRotateString(str1, i);
cout << i <<" : " << ret << endl;
}
}
int main()
{
Test();
return 0;
}