题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则替换之后的字符串为We%20Are%20Happy.
方法一:
class Solution:
def replaceSpace(self,s):
s = list(s)
length = len(s)
for i in range(0,length):
if s[i]==" ":
s[i] = "%20"
return ''.join(s)
所用时间为7.987545844182548e-05方法二:使用从后向前移动字符串元素的方法,Python中字符串作为一个常量,需要通过序列切片的方式组合成新的字符串。
s = "we are happy."
def replace(s):
s_original = s
if s == "":
return None
# 统计原字符串长度
count = 0
# 统计空格数
number_blank = 0
for i in s:
count+=1
if i == " ":
number_blank+=1
original_len = count
new_len = original_len + number_blank*2
index_ori = original_len-1
index_new = new_len-1
# 由*占位扩展之后的字符串长度
s = s+number_blank*2*'*'
# 从后向前遍历
while index_ori>=0 and index_new>index_ori:
# 空格替换成"%20"
if s[index_ori] == " ":
s =s[:index_new]+'0'+s[index_new+1:]
index_new-=1
s = s[:index_new]+'2'+s[index_new+1:]
index_new -= 1
s = s[:index_new]+'%'+s[index_new+1:]
index_new -= 1
# 非空格原样向后粘贴
else:
s = s[:index_new]+s[index_ori]+s[index_new+1:]
index_new -= 1
index_ori-=1
if s == s_original:
return "字符串没有空格"
return s
print(replace(s))
所用时间为:9.559392215126102e-05
方法一时间较少
拓展:有两个排序的列表a和b,把b中所有数字插入到a中
a = [1,3,4,7]
b = [0,5,6,8,9]
for i in range(len(b)):
for j in range(len(a)):
# 当b中元素大于a中最大元素时,直接加在a的后面
if b[i] > a[len(a)-1]:
a.append(b[i])
elif b[i] < a[j]:
a.insert(j, b[i])
break
else:
continue
print(a)