【发布时间】:2016-12-13 23:05:44
【问题描述】:
我正在阅读 Skiena 的《算法设计手册》一书中的“8.2.1 通过recusion 编辑距离”部分。在本节中,我无法理解以下两点。
- D[i,j-1]+1。这意味着文本中有一个额外的字符需要考虑,因此我们不推进模式指针并支付插入成本。
- D[i-1,j]+1。这意味着模式中有一个额外的字符要删除,因此我们不推进文本指针并支付删除成本。
以上两点提到了计算插入和删除距离。我无法理解这个逻辑是如何工作的。似乎对于每一对都假设需要插入和删除。我对吗?为什么每次插入和删除都要加 1?请解释一下这个逻辑是如何工作的。
下面是算法
//we will pass two strings and lengths of those strings
int string_compare(char *s, char *t, int i, int j)
{
int k; /* counter */
int opt[3]; /* cost of the three options */
int lowest_cost; /* lowest cost */
if (i == 0) return(j * indel(’ ’));
if (j == 0) return(i * indel(’ ’));
opt[MATCH] = string_compare(s,t,i-1,j-1) + match(s[i],t[j]);
// *** I could not able to understand below two lines. ***
opt[INSERT] = string_compare(s,t,i,j-1) + indel(t[j]);
opt[DELETE] = string_compare(s,t,i-1,j) + indel(s[i]);
return( min(opt[Match],opt[INSERT],opt[DELETE])); //min function will return min of all three values
}
int match(char c, char d)
{
if (c == d) return(0);
else return(MAXLEN);
}
int indel(char c)
{
return(1);
}
请举例说明。
这不是一个重复的问题。我做了研究,但我找不到任何东西。
【问题讨论】:
-
我的答案和这两个答案的 cmets 可能会对您有所帮助,stackoverflow.com/questions/41036622/…
标签: algorithm