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里面可以直接分割字符串和拼凑字符串的方法

方法二(另外的一种改良版本,代码逻辑不变,更直观):
def replace_space(string):
    count = 0
    for x in string:
        if x==' ':
            count+=3
        else:
            count +=1
    p1 ,p2= len(string)-1,count-1
    newString = [None for x in range(count)]
    while p1>=0 and p2>=0:
        if string[p1]==' ':
            newString[p2] = '0'
            newString[p2-1] = '2'
            newString[p2-2] = '%'
            p2-=3
            p1-=1
        else:
            newString[p2]=string[p1]
            p1-=1
            p2-=1
    return ''.join(newString)
a= 'We are happy.'
print(replace_space(a))
发布了16 篇原创文章 · 获赞 0 · 访问量 161

猜你喜欢

转载自blog.csdn.net/qq_43275748/article/details/102641332