给出以下题目的c++代码。编辑距离:给定两个序列S1和S2,通过一系列字符编辑(插入,删除,替换)等操作,将S1转变成S2,完成这种转换所需要的最少的编辑操作个数成为S1和S2的编辑距离。
时间: 2024-05-07 07:17:34 浏览: 63
好的,以下是求解编辑距离的C语言代码:
```c
#include <stdio.h>
#include <string.h>
#define MIN(x, y) ((x) < (y) ? (x) : (y))
int edit_distance(char *str1, char *str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int dp[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
for (int j = 0; j <= len2; j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + MIN(MIN(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]);
}
}
}
return dp[len1][len2];
}
int main() {
char str1[] = "horse";
char str2[] = "ros";
int distance = edit_distance(str1, str2);
printf("The edit distance between %s and %s is %d\n", str1, str2, distance);
return 0;
}
```
输出是:
```
The edit distance between horse and ros is 3
```
算法采用动态规划,时间复杂度O(m*n),其中m和n分别为两个字符串的长度。
阅读全文