From 5b268b787f0f07e926013c7246469244b95d0169 Mon Sep 17 00:00:00 2001 From: NevS <1173325467@qq.com> Date: Fri, 11 Jun 2021 20:59:12 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC=20go=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 47 ++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 794f9ac5..a4c0149f 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -154,7 +154,54 @@ Python: Go: +```go +// 遍历添加 +func replaceSpace(s string) string { + b := []byte(s) + result := make([]byte, 0) + for i := 0; i < len(b); i++ { + if b[i] == ' ' { + result = append(result, []byte("%20")...) + } else { + result = append(result, b[i]) + } + } + return string(result) +} +// 原地修改 +func replaceSpace(s string) string { + b := []byte(s) + length := len(b) + spaceCount := 0 + // 计算空格数量 + for _, v := range b { + if v == ' ' { + spaceCount++ + } + } + // 扩展原有切片 + resizeCount := spaceCount * 2 + tmp := make([]byte, resizeCount) + b = append(b, tmp...) + i := length - 1 + j := len(b) - 1 + for i >= 0 { + if b[i] != ' ' { + b[j] = b[i] + i-- + j-- + } else { + b[j] = '0' + b[j-1] = '2' + b[j-2] = '%' + i-- + j = j - 3 + } + } + return string(b) +} +```