比较简单,想清楚边界条件,然后做一下字符的反转即可。go 可以将不能变动的字符串转换成可以变动的 []byte
之后,修改完之后,再转成 string
func reverseStr(s string, k int) string {
if len(s) <= 1 {
return s
}
strBytes := []byte(s)
var left, right int
// abcdefg 2
for ; right < len(strBytes); right++ {
if (right-left) >= 2*k-1 || right == len(strBytes)-1 {
if left+k-1 > len(strBytes)-1 {
swapStrBytes(strBytes, left, len(strBytes)-1)
} else {
swapStrBytes(strBytes, left, left+k-1)
}
left = right + 1
}
}
return string(strBytes)
}
func swapStrBytes(s []byte, left, right int) {
if left >= right {
return
}
for left < right {
s[left], s[right] = s[right], s[left]
left++
right--
}
}
标签:right,string,strBytes,len,II,541,swapStrBytes,leetcode,left
From: https://www.cnblogs.com/wudanyang/p/17007103.html