website/content/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:
给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。
要求:
2 * K 长度的字符串,反转前 K 个字符,后 K 个字符串保持不变;对于末尾不够 2 * K 的字符串,如果长度大于 K,那么反转前 K 个字符串,剩下的保持不变。如果长度小于 K,则把小于 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)
}