題目描述
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。
思路1:直接使用python自帶的replace函數進行操作。
python題解
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ','%20')
對replace函數的記錄:
思路2:先遍歷一遍得到空格的個數c,然後初始化len(s)+c*2大小的list,從後往前遍歷s,複製到list從後往前的相應位置,碰到空格進行替換3個,直到走到開頭。
python題解:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
count=0
for cha in s:
if cha==' ':
count=count+1
if count==0:
return s
f_origin=len(s)
f_new=len(s)+2*count
l=[0]*f_new
while f_origin>0:
if s[f_origin-1]!=' ':
l[f_new-1]=s[f_origin-1]
f_origin-=1
f_new-=1
else:
l[f_new-1]='0'
l[f_new-2]='2'
l[f_new-3]='%'
f_origin-=1
f_new-=3
return ''.join(l)