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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值