劍指offer 2 替換空格

2021-08-06 07:21:49 字數 1985 閱讀 1847

請實現乙個函式,將乙個字串中的空格替換成「%20」。

#!/usr/bin/env python

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

# created by xuehz on 2017/8/7

class

solution:

# s 源字串

defreplacespace

(self, s):

# write code here

if type(s) != str:

return

return s.replace(' ', '%20')

defreplacespace1

(self, s):

if s == none:

return

none

if type(s) != str:

return

if len(s) == 0:

return

result = ''

for item in s:

if item.isspace():

result = result + '%20'

else:

result = result + item

return result

# 書中給的思路

defreplacespace2

(self,s):

ifnot isinstance(s, str) or len(s) <= 0

or s == none:

return

'' spacenum = 0

#統計字串中空格的總數

for i in s:

if i == ' ':

spacenum += 1

newstrlen = len(s) + spacenum * 2

#替換後的長度等於原來長度加上2乘以空格的數目

newstr = newstrlen * [none] #[none, none, none, none, none, none, none, none, none, none, none, none, none, none, none, none]

indexoforiginal, indexofnew = len(s) - 1, newstrlen - 1

while indexofnew >= 0

and indexofnew >= indexoforiginal:

if s[indexoforiginal] == ' ':

newstr[indexofnew-2: indexofnew+1] = ['%', '2', '0']

indexofnew -= 3

indexoforiginal -= 1

else:

newstr[indexofnew] = s[indexoforiginal]

indexofnew -= 1

indexoforiginal -= 1

return

"".join(newstr)

if __name__ == '__main__':

test = solution()

print test.replacespace(s)

print test.replacespace1(s)

print test.replacespace2(s)

"""語法:isinstance(object,type)

作用:來判斷乙個物件是否是乙個已知的型別。

其第乙個引數(object)為物件,第二個引數(type)為型別名(int...)或型別名的乙個列表((int,list,float)是乙個列表)。

其返回值為布林型(true or flase)。

"""

劍指offer(2) 替換空格

假設面試官讓我們在原來的字串上做替換。時間複雜度為o n 的解法。我們可以先遍歷一遍字串,這樣就能統計出字串中空格的總數,並可以由此計算出替換之後的字串的總長度。每替換乙個空格,長度增加2,因此替換以後字串的長度等於原來的長度加上2乘以空格數目。length為牛客系統規定字串輸出的最大長度,固定為乙...

劍指Offer 2 替換空格

題目描述 python 實現 coding utf 8 class solution s 源字串 def replacespace self,s write code here count 0 for val in s if val count 1 s new len s count 2 index...

劍指offer 2 替換空格

1.能不能允許連續出現多個空格?2.若有可能連續多個空格,用多個還是單個20 進行替換?1.不會出現連續多個空格 直接用空格將字串切割成陣列,在用20 進行連線。function replacespace str 2.允許出現多個空格,每個空格均用乙個20 替換 用正規表示式找到所有空格依次替換 f...