题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
python代码实现:
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
count = 0
for val in s:
if val == " ":
count += 1
s_new = [""]*(len(s) + count * 2)
index = len(s_new) - 1
for val in s[::-1]:
if val == " ":
s_new[index] = '0'
s_new[index-1] = '2'
s_new[index-2] = '%'
index -= 3
else:
s_new[index] = val
index -= 1
return "".join(s_new)
解析:这道题在python中做起来没有考察点,主要是考虑新字符串的大小,从后往前移动字符,如果s是数组且长度足够大的话,可以在数组内部移动,每个字符最多只需要移动一次