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) +} +```