替换空格

题目描述:

请实现一个函数,将一个字符串中的空格替换成“%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)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值