#include <stdio.h>
#include <string.h>
int min(int a, int b, int c) {
int smallest = a;
if (b < smallest)
smallest = b;
if (c < smallest)
smallest = c;
return smallest;
}
int levenshteinDistance(char* str1, char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int dist[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++)
dist[i][0] = i;
for (int j = 0; j <= len2; j++)
dist[0][j] = j;
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i - 1] == str2[j - 1])
dist[i][j] = dist[i - 1][j - 1];
else
dist[i][j] = min(dist[i - 1][j] + 1, // 删除操作
dist[i][j - 1] + 1, // 插入操作
dist[i - 1][j - 1] + 1); // 替换操作
}
}
return dist[len1][len2];
}
int main() {
char str1[] = "kitten";
char str2[] = "sitting";
int distance = levenshteinDistance(str1, str2);
printf("Levenshtein Distance: %d\n", distance);
return 0;
}
莱文斯坦距离(Levenshtein Distance),也称为编辑距离(Edit Distance),是一种用于衡量两个字符串之间的差异程度的指标。它定义为将一个字符串转换为另一个字符串所需的最少编辑操作次数,允许的编辑操作包括插入、删除和替换字符。