I saw this Levenshtein formula on Wikipedia:
I have implemented this algorithm in a recursive way (I know it is an inefficient way to implement it such a way, but I wanted to see how much inefficient it was), here is the code (in PHP):
function lev($str1, $str2, $i, $j) {
if (min($i, $j) == 0) {
return max($i, $j);
}
else {
$m = ($str1[$i-1] == $str2[$j-1]) ? 0 : 1;
return min(lev($str1, $str2, $i, $j - 1) + 1,
lev($str1, $str2, $i - 1, $j) + 1,
lev($str1, $str2, $i - 1, $j - 1) + $m);
}
}
$str1 = "long long text";
$str2 ="absolute";
echo lev($str1, $str2, strlen($str1),strlen($str2));
When I test it like I did for those two strings (even if "long long text" is not such long) I get a "Max execution time of 30 seconds"..., but the function seems to work with strings where the Levenshtein distance is low (e.g. $str1 = "word", $str2 = "corw")
Exceeding 30 seconds to complete this script is too much, so maybe I have typed something wrong in the implementation (but when I look at the implementation I don't see any error, it seems to me I have wrote the correct algorithm if based on the Wiki's formula)
Is this implementation so slow or am I wrong somewhere in the code?
Thanks for the attention!