5.替换空格

题目:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

时间复杂度为O(n):

class solution(object):
def replace_space(self, string):
num_space = 0
for x in string:
if x == ' ':
num_space += 1
new_lenth = len(string) + 2 * num_space
index_orange = len(string) - 1
index_new = new_lenth - 1
new_string = [None for x in range(new_lenth)]
while index_orange >= 0 :
if string[index_orange] == ' ':
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] = string[index_orange]
index_new -= 1
index_orange -= 1
return ''.join(new_string)

#这里呢采用用空间换时间的思路,开辟一个存储空间,空格存放被换成‘%20’的列表。注意原字符串按字符串,新字符串先用列表再转换成字符串

时间复杂度为O(n2):

方法一:

class solution(object):
  def replace_space(self,string):
    return'%20'.join(string.split(' '))

#很巧妙地运用了python里面可以直接分割字符串和拼凑字符串的方法

 

 

方法二:

class solution(object):
  def replace_space(self,string):
    return string.replace(' ','%20')

#python的某些基本知识有些遗忘  -_-||

 

posted @ 2019-10-17 17:13  明~  阅读(146)  评论(0编辑  收藏  举报