题目:offer 05. 替换空格
题目描述
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。[1]
解题思路
1. 遍历字符串,找到空格,使用replace替换
def replaceSpace(self, s: str) -> str:
for i in range(len(s)):
if s[i] == " ":
s = s.replace(s[i], '%20')
return s
replace函数并不改变原来的字符串,而是返回来一个新的字符串。
有点投机取巧哈,使用replace函数。
2. 变成列表,遍历替换之后,使用join拼接
def replaceSpace(self, s: str) -> str:
l = list(s)
for i in range(len(l)):
if l[i] == ' ':
l[i] = '%20'
return ''.join(l)
references
[1] https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/