-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path541.reverse-string-ii.cpp
More file actions
49 lines (49 loc) · 1.03 KB
/
541.reverse-string-ii.cpp
File metadata and controls
49 lines (49 loc) · 1.03 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
/*
* @lc app=leetcode id=541 lang=cpp
*
* [541] Reverse String II
*/
#include <string>
#include <sstream>
using namespace std;
// @lc code=start
class Solution
{
public:
void rev(string &s, int start, int end, stringstream &ss)
{
for (int i = end - 1; i >= start; i--)
{
if (i < s.length())
ss << s[i];
}
return;
}
string reverseStr(string s, int k)
{
int idx = 0;
stringstream ss;
while (1)
{
bool reverse_flag = (idx / k) % 2 == 0;
if (reverse_flag)
{
rev(s, idx, idx + k, ss);
idx += k;
}
else
{
int max_idx = idx + k;
for (; idx < max_idx; idx++)
{
if (idx < s.length())
ss << s[idx];
}
}
if (idx >= s.length())
break;
}
return ss.str();
}
};
// @lc code=end