(python)《剑指offer》面试题5:替换空格

博客围绕算法展开,主要介绍用Python实现将字符串中每个空格替换成“%20”的函数,给出直觉做法、开辟新存储空间、先遍历找空格等方案,还列举了类似的数组插入排序例子,并展示了执行程序和结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

实现一个函数,把字符串的每个空格替换成“%20”,例如,输入“We are happy!”,输出“We%20are%20happy!”
1. 直觉做法

#直觉做法1:使用内置函数
def replace_space(string):
    return '%20'.join(string.split(' '))


    

    

2.方案二:开辟新的存储空间

def replace_space_1(string):
    string_new = string 
    find = 0
    for index, i in enumerate(string):
        if i == ' ':
            string_new = string_new[:index+find*2] + '%20' + string[index+1:]
            find += 1
    return string_new 
  1. 方案三:先遍历字符串找出所有的空格
def replace_space_2(string):
    origin_len = len(string)
    space_num = 0
    for i in string:
        if i == ' ':
            space_num += 1
    new_len = origin_len + space_num * 2
    index_of_New = new_len - 1
    index_of_origin = origin_len - 1
    string = string + ' ' * space_num * 2
    string = list(string)
    ## python 字符串不能索引赋值
    while index_of_New >= 0 and index_of_New > index_of_origin:
        if string[index_of_origin] == ' ':
            string[index_of_New-2 : index_of_New+1] = ["%","2","0"]
            index_of_New -= 3
            index_of_origin -= 1 
        else:
            string[index_of_New] = string[index_of_origin]
            index_of_New -= 1
            index_of_origin -= 1
    return ''.join(string) 

类似例子

有两个排序的数组A1和A2,内存在A1的末尾有足够的多的空余空间容纳A2。实现一个函数,把A2的所有数字插入到A1,并且所有的数字是排序的

def sort_two_array(array_A, array_B):
    A_len = len(array_A)
    B_len = len(array_B)
    array_A = array_A + [' '] * B_len 
    p1 = A_len - 1
    p2 = A_len + B_len -1
    B_index = B_len - 1
    while p2 >= 0 and p2 > p1:
        if array_A[p1] > array_B[B_index]:
            array_A[p2] = array_A[p1]
            p1 -= 1
            p2 -= 1
        else:
            array_A[p2] = array_B[B_index]
            p2 -= 1
            B_index -= 1
    return array_A

执行程序

if __name__ == '__main__':
    print(replace_space('We are happy'))
    print(replace_space_1('We are happy'))
    print(replace_space_2('We are happy'))
    print(sort_two_array(array_A=[1,2,3,5,7], array_B=[2,5,7,8]))

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值