mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 剑指Offer05.替换空格 go版
This commit is contained in:
@ -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)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user