1 題目描述、要求
題目描述:
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
題目要求:
時間限制:C/C++ 1秒,其他語言2秒 空間限制:C/C++ 32M,其他語言64M
2 分析及題解
2.1 方法一:內置方法str.replace()
時間複雜度:O(n)
'''
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(" ","%20")
2.2 暴力遍歷替換(藉助新字符串)
遍歷遇到空格替換成%20,將此時遍歷元素追加到新字符串
時間複雜度 O(n)
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
newS = ""
for i in s:
if i == " ":
i = "%20"
newS += i
return newS
2.3 方法三:字符串分割+拼接
根據空格分割,用%20連接
時間複雜度O(n)
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return "%20".join(s.split(" "))