思路:Python列表中實現字符串的替換,涉及到頻繁的插入操做,在數據結構中線性表分爲順序表和鏈表,順序表的適合頻繁的查詢,鏈表適合頻繁的插入和刪除。綜上所述,本題使用鏈表來實現。數據結構
咱們從字符串的後面開始複製和替換,設置P1和P2指針,其中P1指向原來字符串的尾部,P2指向替換後字符串的尾部。移動P1指針,依次將P1指向的字符複製到P2,直到遇到第一個空格,在P2以前插入%20,同時P2指針向前移動三次。直到P1和P2指針相遇,則表示替換完畢。指針
全部的字符都複製一次,時間複雜度爲O(n)。code
代碼:blog
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) # 將列表轉爲字符串