我正在阅读“算法设计手册(第二版)”。 C ++对我来说是新的。 我尝试使用作者的示例:string_compare(),并且仅由我自己编写代码main()。输出错误。我猜我的main的char s []指针有问题。 任何人都可以帮助我找到我的错误。
使用C ++编写的代码,输入非常简单
int main()
{
char s[] = "A"; // "thou shalt not"; //"FOOD";
char t[] = "B"; // "you should not"; //"MONEY";
int i = sizeof(s)/sizeof(char);
int j = sizeof(t)/sizeof(char);
int resultDistance = string_compare(s, t, i, j);
printf("N steps = %d\n", resultDistance);
reconstruct_path(s, t, i, j);
}
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]);
opt[INSERT] = string_compare(s,t,i,j-1) + indel(t[j]);
opt[DELETE] = string_compare(s,t,i-1,j) + indel(s[i]);
lowest_cost = opt[MATCH];
for (k=INSERT; k<=DELETE; k++)
if (opt[k] < lowest_cost) lowest_cost = opt[k];
m[i][j].cost = lowest_cost; /* REMOVE FROM PRINTED VERSION */
return( lowest_cost );
}
int reconstruct_path(char *s, char *t, int i, int j)
{
/*printf("trace (%d,%d)\n",i,j);*/
if (m[i][j].parent == -1) return(0);
if (m[i][j].parent == MATCH) {
reconstruct_path(s,t,i-1,j-1);
match_out(s, t, i, j);
return(0);
}
if (m[i][j].parent == INSERT) {
reconstruct_path(s,t,i,j-1);
insert_out(t,j);
return(0);
}
if (m[i][j].parent == DELETE) {
reconstruct_path(s,t,i-1,j);
delete_out(s,i);
return(0);
}
}
int match_out(char *s, char *t, int i, int j)
{
if (s[i]==t[j]) printf("M");
else printf("S");
return(0);
}
void insert_out(char *t, int j)
{
printf("I");
}
void delete_out(char *s, int i)
{
printf("D");
}
int indel(char c)
{
return(1);
}
int match(char c, char d)
{
if (c == d) return(0);
else return(1);
}
我在github上的代码:https://github.com/hoangvu1991/EditDistanceRecursive/blob/master/EditDistanceRecursive.cpp
实际:0 |期望:1
答案 0 :(得分:1)
尝试以下操作:
opt[MATCH] = string_compare(s,t,i-1,j-1) + match(s[i-1],t[j-1]);
代替
opt[MATCH] = string_compare(s,t,i-1,j-1) + match(s[i],t[j]);