Mark Byers..
9
递归函数具有O(n ^ 2)性能,因为它在每次找到匹配时复制字符串的剩余内容.这比迭代解O(n)慢,并且不必要地如此.
您可以轻松地将其重写为更快,同时通过将搜索的起始索引作为可选参数传递给函数来简化代码并扩展其功能:
def countSubStringMatchRecursive(target, key, start_index = 0):
index = target.find(key, start_index)
if index >= 0:
return countSubStringMatchRecursive(target, key, index + len(key)) + 1
return 0
target_string = 'an apple and a banana'
key = 'an'
count = countSubStringMatchRecursive(target_string, key)
print "Number of instances of %r in %r is %d" % (key, target_string, count)
输出:
Number of instances of 'an' in 'an apple and a banana' is 4
更新:如果您真的想使用字符串模块的查找功能,只需更改一行即可:
index = find(target, key, start_index)