题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
这道题出的应该不是replace…
class Solution:
# s 源字符串运行时间:33ms
#
# 占用内存:5752k
def replaceSpace(self, s):
s = s.replace(' ','%20')
return s
if __name__ == '__main__':
solution = Solution()
print(solution.replaceSpace('We are happy.'))
面试完阿里,面试官一直虐我复杂度。决定重新写一下这个题O(n)的做法
def replaceSpace3(self, s):
if not 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
newStr = newStrLen * [None] # 给一个列表,里面有newstrlen个none
indexOfOriginal, indexOfNew = len(s) - 1, newStrLen - 1 # 两个索引,一个是12 一个是16
while indexOfNew >= 0 and indexOfNew >= indexOfOriginal:
if s[indexOfOriginal] == ' ': # 当为空格时,新索引-3,旧索引-1,并且新列表的位置为['%', '2', '0']
newStr[indexOfNew-2:indexOfNew+1] = ['%', '2', '0']
indexOfNew -= 3
indexOfOriginal -= 1
else:
newStr[indexOfNew] = s[indexOfOriginal] #把就索引指向的值赋给新索引,两个索引各减1
indexOfNew -= 1
indexOfOriginal -= 1
return "".join(newStr) # 最后拼接起来