541. Reverse String II #
Problem #
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:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
Problem Summary #
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 fewer than k characters left, reverse all the remaining characters. If there are fewer than 2k but greater than or equal to k characters, reverse the first k characters and leave the remaining characters as they are.
Requirements:
- The string contains only lowercase English letters.
- The length of the given string and k are in the range [1, 10000].
Solution Ideas #
- The requirement is to reverse the string according to certain rules: for every substring of length
2 * K, reverse the firstKcharacters, while keeping the latterKcharacters unchanged; for the substring at the end that is shorter than2 * K, if its length is greater thanK, then reverse the firstKcharacters and keep the rest unchanged. If its length is less thanK, then reverse this entire substring of length less thanK. - This is an easy problem; just reverse the string according to the problem statement.
Code #
package leetcode
func reverseStr(s string, k int) string {
if k > len(s) {
k = len(s)
}
for i := 0; i < len(s); i = i + 2*k {
if len(s)-i >= k {
ss := revers(s[i : i+k])
s = s[:i] + ss + s[i+k:]
} else {
ss := revers(s[i:])
s = s[:i] + ss
}
}
return s
}
func revers(s string) string {
bytes := []byte(s)
i, j := 0, len(bytes)-1
for i < j {
bytes[i], bytes[j] = bytes[j], bytes[i]
i++
j--
}
return string(bytes)
}