-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path42_2_LeftRotateString.cpp
More file actions
60 lines (44 loc) · 1023 Bytes
/
42_2_LeftRotateString.cpp
File metadata and controls
60 lines (44 loc) · 1023 Bytes
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
# include <iostream>
# include <cstdlib>
# include <vector>
# include <string>
using namespace std;
void display_vec(vector<int> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
void display_vec(vector<string> &vec)
{
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl;
}
void reverse(string &str, int start, int end)
{
for (int i = start, j = end; i < j; i++, j--)
swap(str[i], str[j]);
}
string LeftRotateString(string str, int n)
{
if (str.size() <= 1 || n <= 0 || str.size() <= n)
return str;
// reverse whole string
int len = str.size();
reverse(str, 0, len - 1);
// reverse separate part
reverse(str, 0, len - n - 1);
reverse(str, len - n, len - 1);
return str;
}
int main(int argc, char *argv[])
{
string str = "abcdefg";
int n = 2;
string res;
cout << str << endl;
res = LeftRotateString(str, n);
cout << res << endl;
return 0;
}