请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
主要思路:
1.用python字符串的replace方法。
2.对空格split得到list,用‘%20’连接(join)这个list。
3.由于替换空格后,字符串长度需要增大。先扫描空格个数,计算字符串应有的长度,从后向前一个个字符复制(需要两个指针)。这样避免了替换空格后,需要移动的操作。
遍历一次字符串,这样就可以统计出字符串空格的总数,并可以由此计算出替换之后的字符串的总长度。每替换一个空格,长度增加2,因此替换以后字符串的长度等于原来的长度加上2乘以空格数目。以"We are happy"为例,"We are happy"这个字符串的长度为14(包括结尾符号"\n"),里面有两个空格,因此替换之后字符串的长度是18。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
num_space = 0
for i in s:
if i == ' ':
num_space += 1
new_length = len(s) + 2 * num_space
index_origin = len(s) - 1
index_new = new_length - 1
# 开辟一个新的列表的保存结果
new_string = [None for i in range(new_length)]
# 按顺序往新列表里放
while index_origin >= 0:
if s[index_origin] == ' ':
new_string[index_new] = '0'
index_new -= 1
new_string[index_new] = '2'
index_new -= 1
new_string[index_new] = '%'
index_new -= 1
else:
new_string[index_new] = s[index_origin]
index_new -= 1
index_origin -= 1
return ''.join(new_string)
另外也可以只在一个列表上操作,直接在原来的列表开辟出新的空间,用两个指针,一个字符串的末尾,另一个指向整个列表的末尾。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
num_space = 0
a = []
for i in s:
if i == ' ':
num_space += 1
a.append(i)
new_length = len(s) + 2 * num_space
for i in range(len(s),new_length):
a.append(None)
p1 = len(s)-1
p2 = new_length-1
while p1>=0:
if a[p1]==' ':
a[p2]='0'
p2-=1
a[p2]='2'
p2-=1
a[p2]='%'
p2-=1
else:
a[p2] = a[p1]
p2-=1
p1-=1
return ''.join(a)