#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "fuzzy/common.h"
unsigned levenshtein(const char* str1, const char* str2) {
assert(str1 != NULL);
assert(str2 != NULL);
size_t str1_len = strlen(str1);
size_t str2_len = strlen(str2);
if (str1_len == 0) {
return str2_len;
}
if (str2_len == 0) {
return str1_len;
}
while (str1_len > 0 && str2_len > 0 && EQ(str1[0], str2[0])) {
str1++, str2++;
str1_len--, str2_len--;
}
unsigned row, col;
unsigned last_diag = 0, cur, cost;
unsigned* vector = calloc(str1_len + 1, sizeof(unsigned));
for (col = 1; col <= str1_len; col++) {
vector[col] = col;
}
for (row = 1; row <= str2_len + 1; row++) {
vector[0] = row;
last_diag = row - 1;
for (col = 1; col <= str1_len; col++) {
cur = vector[col];
cost = EQ(str1[col - 1], str2[row - 1]) ? 0 : 1;
vector[col] = MIN3(vector[col] + 1, vector[col - 1] + 1, last_diag + cost);
last_diag = cur;
}
}
free(vector);
return last_diag;
}