leetcode-541. 反转字符串 II

541. 反转字符串 II - 力扣(Leetcode)

比较简单,想清楚边界条件,然后做一下字符的反转即可。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--
}
}
posted @   吴丹阳-V  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示