【发布时间】:2015-03-14 10:14:58
【问题描述】:
我想知道以下算法的复杂性是多少,最重要的是,我想知道导致推导它的逐步过程。
我怀疑它是 O(length(text)^2*length(pattern)) 但我无法求解递归方程。
在对递归调用进行记忆化(即动态编程)时,复杂性会如何提高?
另外,我希望能提供一些技术/书籍,它们可以帮助我学习如何分析这种算法。
在 Python 中:
def count_matches(text, pattern):
if len(pattern) == 0: return 1
result = 0
for i in xrange(len(text)):
if (text[i] == pattern[0]):
# repeat the operation with the remaining string a pattern
result += count_matches(text[i+1:], pattern[1:])
return result
在 C 中:
int count_matches(const char text[], int text_size,
const char pattern[], int pattern_size) {
if (pattern_size == 0) return 1;
int result = 0;
for (int i = 0; i < text_size; i++) {
if (text[i] == pattern[0])
/* repeat the operation with the remaining string a pattern */
result += count_matches(text+i, text_size-(i+1),
pattern+i, pattern_size-(i+1));
}
return result;
}
注意:算法有意对每个子字符串重复匹配。请不要关注算法正在执行什么样的匹配,只关注它的复杂性。
对算法中的(现已修复的)拼写错误表示歉意
【问题讨论】:
-
我认为这两个例子一定是错,而且它们并不完全相同
-
python 版本有一些拼写错误:第 2 行有一个
tex变量,第 8 行有一个count()调用。此外,如果pattern比@987654326 短,python 版本会失败@。如果你只是在寻找一个字符串比较算法,prolly 你可以在没有递归的情况下实现。 -
@user2464424 谢谢,我更正了(我从C算法开始并添加了python以扩大受众范围)
-
@AnttiHaapala 他们怎么错了和不相同?
-
在递归调用中,C版
text+i, text_size-(i+1), pattern+i, pattern_size-(i+1)的参数应该是text+i+1, text_size-(i+1), pattern+1, pattern_size-1,根据Python版本?第一个第三个参数好像不对O_O...