Skip to content

Commit bbb5809

Browse files
committed
add list way
1 parent 78d7ac4 commit bbb5809

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

Target Offer/替换空格.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,27 @@
66
# -*- coding:utf-8 -*-
77
class Solution:
88
# s 源字符串
9-
9+
10+
def replaceSpaceByList(self, s):
11+
s = list(s)
12+
for i in range(len(s)):
13+
if s[i] == ' ':
14+
s[i] = '%20'
15+
return ''.join(s)
16+
1017
# 使用append一次遍历即可替换
1118
# 由于list的append是O(1)的时间复杂度,除了扩容所导致的时间损耗,该算法复杂度为O(n)
1219
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)
20+
string = list(s)
21+
stringReplace = []
22+
for item in string:
23+
if item == ' ':
24+
stringReplace.append('%')
25+
stringReplace.append('2')
26+
stringReplace.append('0')
27+
else:
28+
stringReplace.append(item)
29+
return "".join(stringReplace)
2330

2431
# 创建新的字符串进行替换
2532
def replaceSpace1(self, s):
@@ -70,3 +77,4 @@ def replaceSpace3(self, s):
7077
print(test.replaceSpace1(s))
7178
print(test.replaceSpace2(s))
7279
print(test.replaceSpace3(s))
80+
print(test.replaceSpaceByList(s))

0 commit comments

Comments
 (0)