From 5b4249d4a853a77e9aed0af171204c9b8d0ee2ac Mon Sep 17 00:00:00 2001 From: liuyiwei <709224218@qq.com> Date: Thu, 1 Jun 2023 16:34:00 +0800 Subject: [PATCH] =?UTF-8?q?151.=E7=BF=BB=E8=BD=AC=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E9=87=8C=E7=9A=84=E5=8D=95=E8=AF=8D=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E4=BD=BF=E7=94=A8=E4=BA=86=E7=A7=BB=E9=99=A4=E5=85=83?= =?UTF-8?q?=E7=B4=A0=E6=80=9D=E6=83=B3=E7=9A=84=20Go=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...14\347\232\204\345\215\225\350\257\215.md" | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" index 4474f1c613..6dd3cd4975 100644 --- "a/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" +++ "b/problems/0151.\347\277\273\350\275\254\345\255\227\347\254\246\344\270\262\351\207\214\347\232\204\345\215\225\350\257\215.md" @@ -467,9 +467,57 @@ class Solution: return " ".join(words) ``` - Go: +版本一: + +```go +func reverseWords(s string) string { + b := []byte(s) + + // 移除前面、中间、后面存在的多余空格 + slow := 0 + for i := 0; i < len(b); i++ { + if b[i] != ' ' { + if slow != 0 { + b[slow] = ' ' + slow++ + } + for i < len(b) && b[i] != ' ' { // 复制逻辑 + b[slow] = b[i] + slow++ + i++ + } + } + } + b = b[0:slow] + + // 翻转整个字符串 + reverse(b) + // 翻转每个单词 + last := 0 + for i := 0; i <= len(b); i++ { + if i == len(b) || b[i] == ' ' { + reverse(b[last:i]) + last = i + 1 + } + } + return string(b) +} + +func reverse(b []byte) { + left := 0 + right := len(b) - 1 + for left < right { + b[left], b[right] = b[right], b[left] + left++ + right-- + } +} +``` + +版本二: + ```go import ( "fmt"