我正在解决CTCI中的一个问题。
第一章的第三个问题要求你将像
'Mr John Smith '
这样的字符串中的空格替换为%20
:
'Mr%20John%20Smith'
作者提供了这个Python解决方案,并称其为O(n):
def urlify(string, length):
'''function replaces single spaces with %20 and removes trailing spaces'''
counter = 0
output = ''
for char in string:
counter += 1
if counter > length:
return output
elif char == ' ':
output = output + '%20'
elif char != ' ':
output = output + char
return output
我的问题:
我知道在实际扫描字符串时,从左到右的时间复杂度是O(n)。但是Python中的字符串不可变,如果我有一个字符串并使用 +
操作符将另一个字符串添加到它中,它不会分配必要的空间,然后复制原始字符串并复制追加的字符串吗?
如果我有一个长度为1的包含n
个字符串的集合,那么它需要:
1 + 2 + 3 + 4 + 5 + ... + n = n(n+1)/2
或者O(n^2) 时间,对吗?或者我对Python中的追加方式存在误解?
或者,如果您愿意教我钓鱼的技巧:我该如何自己找到答案?我尝试了在Google上查找官方来源,但一无所获。我找到了https://wiki.python.org/moin/TimeComplexity,但这没有关于字符串的内容。
urllib.urlencode
的事。 - wimrtrim
和replace
会更受欢迎,并且在O(n)
的范围内。复制字符串似乎是最低效的方法。 - OneCricketeer