题目
【剑指offer】005.替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
解法
解法1
掉包
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(' ', '%20')
解法2
直接遍历,时间O(n),空间O(1)
class Solution:
def replaceSpace(self, s: str) -> str:
ins = "%20"
if len(s)==0:
return s
if s==" ":
return ins
i = 0
while i<len(s):
if s[i] == ' ':
if i==0:
s = ins + s[1:]
i = i+3
elif i==len(s)-1:
s = s[0:i]+ins
return s
else:
s = s[0:i] + ins +s[i+1:]
i = i+3
else:
i = i+1
return s