# 541. Reverse String II

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.

Example:

``````Input: s = "abcdefg", k = 2
Output: "bacdfeg"
``````

Restrictions:

1. The string consists of lower English letters only.
2. Length of the given string and k will in the range [1, 10000]

``````class Solution {
public:
string reverseStr(string s, int k) {
int n = s.size(), cnt = n / k;
for (int i = 0; i <= cnt; ++i) {
if (i % 2 == 0) {
if (i * k + k < n) {
reverse(s.begin() + i * k, s.begin() + i * k + k);
} else {
reverse(s.begin() + i * k, s.end());
}
}
}
return s;
}
};
``````

``````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;
}
};
``````

Reverse String

https://discuss.leetcode.com/topic/82652/one-line-c/2

https://discuss.leetcode.com/topic/82626/java-concise-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation