递推实现:
int CalculateDis_DP(char *str1,char *str2)
{
int i, j;
int len1=strlen(str1), len2=strlen(str2);
for (i=0; i<=len2; i++)
d[0][i] = i;
for (i=0; i<=len1; i++)
d[i][0] = i;
for (i=1; i<=len1; i++)
for (j=1; j<=len2; j++)
{
int cost = (str1[i] == str2[j]) ? 0 : 1;
int deletion = d[i-1][j] + 1;
int insertion = d[i][j-1] + 1;
int substitution = d[i-1][j-1] + cost;
d[i][j] = min(deletion,insertion,substitution);
}
return d[len1][len2];
}
递归实现:
int CalculateDis_Recurse(char str1[], int astart, int aend, char str2[], int bstart, int bend)
{
if (astart > aend)
{
if (bstart < bend)
return bend-bstart+1;
else
return 0;
}
if (bstart > bend)
{
if (astart < aend)
return aend-astart+1;
else
return 0;
}
if (str1[astart] == str2[bstart])
{
return CalculateDis_Recurse(str1, astart+1, aend, str2, bstart+1, bend);
}
else
{
int min1 = CalculateDis_Recurse(str1, astart+1, aend, str2, bstart, bend);
int min2 = CalculateDis_Recurse(str1, astart, aend, str2, bstart+1, bend);
int min3 = CalculateDis_Recurse(str1, astart+1, aend, str2, bstart+1, bend);
return min(min1,min2,min3)+1;
}
}