1. 题目内容
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 :
输入:s = "We are happy."
输出:"We%20are%20happy."
---------------------------------------------------------------------------------------------------------------------------------
来源:力扣(LeetCode)
2. 解题思路
其实就是实现python中replace()函数功能
首先可以创建一个空字符串,然后遍历输入的字符串;主要过程是将原字符串中的字符逐个存入新字符串中,并同时判断原字符串中是否有空格,有则替换。
3. python实现
class Solution:
def replaceSpace(self, s):
new_s = '' #新建空字符串
for i in s:
if i == ' ': #判断原字符串中是否有空格
new_s += '%20'
else:
new_s += i
return new_s
if __name__ == '__main__':
a = Solution()
s = 'We are happy'
print(a.replaceSpace(s))
#通过replace()函数实现替换
s = 'We are happy'
#replace()中第一个参数传入需要被替换的字符,第二个参数是新的字符
new_s = s.replace(' ', '%20')
print(new_s)
4. 复杂度
时间和空间复杂度都是O(n)