思想
- 使用字符串內置函數replace直接替換,這樣雖然方便,但是我們並不知道它的算法時間複雜度,儘管他很快。
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(" ","%20")
- 從一般性考慮,就是在不知道有這個內置函數的時候
# 方法二:從C語言的角度考慮
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
string = ""
strLen = len(s)
for i range(strLen):
if s[i] == " ":
string += "%20"
else:
string += s[i]
return string