# 动态规划解字符串编辑距离（C语言实现）

### 递归求解

``````#include<stdio.h>
#include <string.h>

#define min(x,y)  ( x<y?x:y )
int abs( int num );

int EditDistance(char* src, char* dest){
if(strlen(src) == 0 || strlen(dest) == 0)
return abs((int)strlen(src) - (int)strlen(dest));
if(src[0] == dest[0])
return EditDistance(src + 1, dest + 1);
int edIns = EditDistance(src, dest + 1) + 1;
int edDel = EditDistance(src + 1, dest) + 1;
int edRep = EditDistance(src + 1, dest + 1) + 1;

return min(min(edIns,edDel),edRep);
}

int main(){
printf("%d\n", EditDistance("snowy", "sunny"));
}``````

### 动态规划

d[i,j]=d[i-1,j-1] + 0; source[i]等于target[j]
d[i,j]=min(d[i,j-1]+1, d[i-1,j-1]+1, d[i-1,j]+1); source[i]不等于target[j]

d[i,0] = source字符串的长度
d[0,j] = target字符串的长度

``````#include<stdio.h>
#include <string.h>

#define MAX_STRING_LEN 10
#define min(x,y)  ( x<y?x:y )

int EditDistance(char* src, char* dest){
int i,j;
int d[MAX_STRING_LEN][MAX_STRING_LEN] = {0};

for (i = 0; i < (int)strlen(src); ++i) {
d[i][0] = i;
}
for (j = 0; j < (int)strlen(dest); ++j) {
d[0][j] = j;
}
for(i=1; i <= (int)strlen(src); i++){
for(j = 1; j <= (int)strlen(dest); j++){
if(src[i-1]==dest[j-1]){
d[i][j] = d[i-1][j-1];
}else{
int edIns = d[i][j-1] + 1;
int edDel = d[i-1][j]+1;
int edRep = d[i-1][j-1]+1;

d[i][j] =min(min(edIns,edDel),edRep);
}
}
}
for(int m = 0; m < MAX_STRING_LEN; m++){
for(int n = 0; n < MAX_STRING_LEN; n++)
printf("%d",d[m][n]);
printf("\n");
}

return d[strlen(src)][strlen(dest)];
}

int main(){
printf("%d\n", EditDistance("snowy", "sunny"));
}``````