劍指offer Python版 替換空格

2021-08-18 06:31:32 字數 797 閱讀 2065

問題1:替換字串,是在原來的字串上做替換,還是可以重新定義乙個字串做替換:

問題2:從前往後替換和從後往前替換一樣嗎?

從左往右遍歷元素,若當前元素為空格,則插入「%20」, 並將字串長度增加3. 時間複雜度o(n * n).

# -*- coding:utf-8 -*-

class solution:

# s 源字串

def replacespace(self, s):

# write code here

position = 0

while position < len(s):

if s[position] == ' ':

s = s[:position] + '%20' + s[position + 1:]

position += 3

else:

position += 1

return s

占用記憶體:5736k

時間複雜度o(n * n)

# -*- coding:utf-8 -*-

class solution:

# s 源字串

def replacespace(self, s):

# write code here

s = list(s)

for i in range(len(s)):

if s[i] == ' ':

s[i] = '%20'

return ''.join(s)

占用記憶體:5736k

劍指offer(python版) 2 替換空格

牛客網 leetcode 1 暴力解題 replace直接替換 2 從前向後記錄 數目,從前向後替換 class solution s 源字串 def replacespace self,s write code here 方法一 暴力解題 replace函式替換 s s.replace 20 re...

劍指offer Python3版 五

q 輸入乙個整數陣列,實現乙個函式來調整該陣列中數字的順序,使得所有的奇數字於陣列的前半部分,所有的偶數字於陣列的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。你要是這樣寫 class solution def reorderarray self,list1 evenlist,oddli...

劍指offer Python3版 九

q 請實現 copyrandomlist 函式,複製乙個複雜鍊錶。在複雜鍊錶中,每個節點除了有乙個 next 指標指向下乙個節點,還有乙個 random 指標指向鍊錶中的任意節點或者 null 思路 複製鍊錶 cur a b c cloned a b c 複製的鍊錶依次加到原煉表後 a a b b ...