zoukankan      html  css  js  c++  java
  • 剑指offer——02替换空格(Python3)

    思路:Python列表中实现字符串的替换,涉及到频繁的插入操作,在数据结构中线性表分为顺序表和链表,顺序表的适合频繁的查询,链表适合频繁的插入和删除。综上所述,本题使用链表来实现。

     我们从字符串的后面开始复制和替换,设置P1和P2指针,其中P1指向原来字符串的尾部,P2指向替换后字符串的尾部。移动P1指针,依次将P1指向的字符复制到P2,直到遇到第一个空格,在P2之前插入%20,同时P2指针向前移动三次。直到P1和P2指针相遇,则表示替换完毕。

    所有的字符都复制一次,时间复杂度为O(n)。

    代码:

    class Solution:
    # s 源字符串
    def replaceSpace(self, s):
    # write code here
    str_array = list(s) # 将字符串转为列表
    origin_str_length = len(str_array)#列表长度
    origin_index = origin_str_length - 1#尾指针
    new_str_array = []
    while origin_index >= 0:#终止条件
    if str_array[origin_index] != ' ':
    new_str_array.insert(0, str_array[origin_index])
    else:
    new_str_array.insert(0, '%20')
    origin_index -= 1
    return "".join(new_str_array) # 将列表转为字符串
  • 相关阅读:
    129. Sum Root to Leaf Numbers
    113. Path Sum II
    114. Flatten Binary Tree to Linked List
    112. Path Sum
    100. Same Tree
    300. Longest Increasing Subsequence
    72. Edit Distance
    自定义js标签库
    JS 实现Table相同行的单元格自动合并示例代码
    mysql 高版本only_full_group_by 错误
  • 原文地址:https://www.cnblogs.com/wobushangwangl/p/10922519.html
Copyright © 2011-2022 走看看