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

题目

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

结果

(python)《剑指offer》面试题5:替换空格_第1张图片

你可能感兴趣的:((python)《剑指offer》面试题5:替换空格)