請實現一個函數,把字符串 s 中的每個空格替換成"%20"。
示例 1:
輸入:s = "We are happy."
輸出:"We%20are%20happy."
方法1:Python內置字符串替換函數replace:
class Solution:
def replaceSpace(self, s: str) -> str:
s = s.replace(' ','%20')
return s
結果很好:
看來python的內置函數還是很高效的O(∩_∩)O
方法2:
逐個遍歷字符串中的字符,發現空格則替換爲'%20',代碼如下:
class Solution:
def replaceSpace(self, s: str) -> str:
index_flag = 0
s1 = s
for index,value in enumerate(s):
if value == ' ':
index = index + index_flag
s1 = s1[:index] + '%20' + s1[index+1:] # 要保證s不會變
index_flag = index_flag + 2 # 每替換一次都index都要加2
return s1
時間複雜度O(N),空間複雜度O(N).
但在實現該方法的過程中遇到了幾個問題:
Error1:執行報錯TypeError: 'str' object does not support item assignment
>>> a[1]='%20'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
這個錯誤的原因是
在python中,字符串是不可變對象,不能通過下標的方式直接賦值修改。同樣的不可變對象還有:數字、字符串和元組。
爲此纔有了上述代碼中的倒數第三行:
s1 = s1[:index] + '%20' + s1[index+1:]
Error2: 替換位置出錯,總是在不該替換的地方替換。
錯誤代碼和結果如下:
# 錯誤示範!
class Solution:
def replaceSpace(self, s: str) -> str:
for index,value in enumerate(s):
if value == ' ':
s = s[:index] + '%20' + s[index+1:]
return s
錯誤原因:
每次對s進行替換後s就已經變了,繼續用enumerate進行操作index就會錯位,從而導致錯誤。因此需要使用s1作爲輔助變量,使s與替換無關。同時用index+2來尋找正確的位置。