Skip to content

Commit 85dea78

Browse files
authored
Update 替换空格.py
replace1方法和replace2方法都是O(n*m)的时间复杂度,这里m是空格的数量,因为list的insert是一个O(n)的复杂度。 而list的append是一个O(1)的时间复杂度,除了扩容时的时间损耗,append方法只需要遍历一次数组即可得结果。
1 parent f1b9f60 commit 85dea78

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

Target Offer/替换空格.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@
66
# -*- coding:utf-8 -*-
77
class Solution:
88
# s 源字符串
9+
10+
# 使用append一次遍历即可替换
11+
# 由于list的append是O(1)的时间复杂度,除了扩容所导致的时间损耗,该算法复杂度为O(n)
12+
def replaceSpaceByAppend(self, s):
13+
string = list(string)
14+
stringReplace = []
15+
for item in string:
16+
if item == ' ':
17+
stringReplace.append('%')
18+
stringReplace.append('2')
19+
stringReplace.append('0')
20+
else:
21+
stringReplace.append(item)
22+
return "".join(stringReplace)
923

1024
# 创建新的字符串进行替换
1125
def replaceSpace1(self, s):

0 commit comments

Comments
 (0)