0%

reverse-string-ii

Reverse String II – LeetCode 541

Problem

Description

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0; i < s.size(); i += 2 * k) {
reverse(s.begin() + i, min(s.begin() + i + k, s.end()));
}
return s;
}
};

代码

直接做,写法很妙。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$4$ ms,排名$1.99\%$

Better

思路

还没看到更好的思路