题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路:
(1)遍历字符串,统计出字符串中空格的总数。
(2)替换后字符串的长度 = 原字符串长度 + 2*空格数目。
(3)从替换字符串的后面开始复制和替换。
def replace_str(str):
temp = list(str) # 字符串转换为列表
length = len(temp) # 字符串长度
count = 0 # 空格计数
for tmp in temp:
if tmp ==" ":
count += 1
temp1 = temp + [' ']*2*count
start = length-1 # 定义前指针
end = len(temp1)-1 # 定义后指针
for i in range(length-1, -1, -1):
if start!=end:
if temp[i]!=" ":
temp1[end] = temp[i]
end -= 1
else:
for s in ['0','2','%']:
temp1[end] = s
end -= 1
start -= 1
print("".join(temp1))
if __name__=="__main__":
str = "We are happy."
replace_str(str)