diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 512360fe..63499b71 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -318,9 +318,61 @@ class Solution { Python: - Go: +```go +import ( + "fmt" +) + +func reverseWords(s string) string { + //1.使用双指针删除冗余的空格 + slowIndex, fastIndex := 0, 0 + b := []byte(s) + //删除头部冗余空格 + for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' { + fastIndex++ + } + //删除单词间冗余空格 + for ; fastIndex < len(b); fastIndex++ { + if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' { + continue + } + b[slowIndex] = b[fastIndex] + slowIndex++ + } + //删除尾部冗余空格 + if slowIndex-1 > 0 && b[slowIndex-1] == ' ' { + b = b[:slowIndex-1] + } else { + b = b[:slowIndex] + } + //2.反转整个字符串 + reverse(&b, 0, len(b)-1) + //3.反转单个单词 i单词开始位置,j单词结束位置 + i := 0 + for i < len(b) { + j := i + for ; j < len(b) && b[j] != ' '; j++ { + } + reverse(&b, i, j-1) + i = j + i++ + } + return string(b) +} + +func reverse(b *[]byte, left, right int) { + for left < right { + (*b)[left], (*b)[right] = (*b)[right], (*b)[left] + left++ + right-- + } +} +``` + + + @@ -328,4 +380,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 648546c1..39c8382c 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -23,7 +23,7 @@ https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/ 示例 2: 输入: s = "lrloseumgh", k = 6 输出: "umghlrlose" -  + 限制: 1 <= k < s.length <= 10000 @@ -119,9 +119,31 @@ class Solution { ``` Python: - Go: +```go +func reverseLeftWords(s string, n int) string { + b := []byte(s) + // 1. 反转前n个字符 + // 2. 反转第n到end字符 + // 3. 反转整个字符 + reverse(b, 0, n-1) + reverse(b, n, len(b)-1) + reverse(b, 0, len(b)-1) + return string(b) +} +// 切片是引用传递 +func reverse(b []byte, left, right int){ + for left < right{ + b[left], b[right] = b[right],b[left] + left++ + right-- + } +} +``` + + + @@ -129,4 +151,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file