请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
python
# 剑指005-替换空格
class Solution:
def replaceSpace1(self, s: str) -> str:
"""
遍历字符串,时间O(n), 空间O(n)
:param s:
:return:
"""
res = []
for i in range(len(s)):
if s[i] == ' ':
res.append("%20")
else:
res.append(s[i])
return ''.join(res)
def replaceSpace2(self, s: str) -> str:
"""
扩充字符串+双指针
:param s:
:return:
"""
cnt = 0
for i in s:
if i == ' ':
cnt += 1
res = [""] * (len(s) + 2*cnt)
i = len(s) - 1
j = len(s) + 2*cnt - 1
while i >= 0:
if s[i] != ' ':
res[j] = s[i]
j -= 1
else:
res[j-2] = '%'
res[j-1] = '2'
res[j] = '0'
j -= 3
i -= 1
return ''.join(res)
if __name__ == "__main__":
s = "sky is blue "
test = Solution()
print(test.replaceSpace1(s))
print(test.replaceSpace2(s))
golang
package main
import (
"fmt"
"strings"
)
func main() {
s := "blue is my skay"
fmt.Println(replaceSpace1(s))
}
// 遍历字符串
func replaceSpace1(s string) string {
res := []string{}
for i := 0; i < len(s); i++ {
if string(s[i]) == " " {
res = append(res, "%20")
} else {
res = append(res, string(s[i]))
}
}
return strings.Join(res, "")
}