website/content.en/ChapterFour/0500~0599/0541.Reverse-String-II.md
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:
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:
2 * K, reverse the first K characters, while keeping the latter K characters unchanged; for the substring at the end that is shorter than 2 * K, if its length is greater than K, then reverse the first K characters and keep the rest unchanged. If its length is less than K, then reverse this entire substring of length less than K.
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)
}