mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -154,7 +154,54 @@ Python:
|
|||||||
|
|
||||||
|
|
||||||
Go:
|
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