-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_string2.cpp
More file actions
67 lines (62 loc) · 1.35 KB
/
reverse_string2.cpp
File metadata and controls
67 lines (62 loc) · 1.35 KB
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
/*
* =====================================================================================
*
* Filename: reverse_string2.cpp
*
* Description: 541. Reverse String II.
*
* Version: 1.0
* Created: 04/09/19 12:56:46
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
class Solution
{
public:
std::string reverseStr(std::string& s, int k)
{
if (k < 2)
{
return s;
}
for (int i = 0; i < s.size(); i += (2 * k))
{
int j = i + k - 1;
if (j >= s.size())
{
j = s.size() - 1;
}
reverseStr(s, i, j);
}
return s;
}
private:
void reverseStr(std::string& s, int i, int j)
{
char chr;
while (i < j)
{
chr = s[i];
s[i] = s[j];
s[j] = chr;
i++;
j--;
}
}
};
int main(int argc, char* argv[])
{
std::string s = "abcdefg";
int k = 2;
auto r = Solution().reverseStr(s, k);
printf("Input: `%s`\nOutput: `%s`\n", s.c_str(), r.c_str());
return 0;
}