View Single Post
  #1  
Old 10-28-2009, 05:06 AM
WhiteDragon WhiteDragon is offline
Banned
Join Date: Feb 2007
Posts: 1,002
WhiteDragon is a splendid one to beholdWhiteDragon is a splendid one to beholdWhiteDragon is a splendid one to beholdWhiteDragon is a splendid one to beholdWhiteDragon is a splendid one to behold
Levenshtein Distance

Calculate the distance between two strings temp.s and temp.t.

This is an implementation of the dynamic programming approach. Time complexity of O(m*n).

For an explanation of the algorithm, see the Wikipedia article.

PHP Code:
function levenshtein(temp.stemp.t) {
  
temp.temp.s.length();
  
temp.temp.t.length();
  
  
temp.= new[temp.m][temp.n];
  for (
temp.0temp.<= temp.mtemp.i++) {
    
temp.d[temp.i][0] = temp.i;
  }
  for (
temp.0temp.<= temp.ntemp.j++) {
    
temp.d[0][temp.j] = temp.j;
  }
  
  for (
temp.1temp.<= temp.ntemp.j++) {
    for (
temp.1temp.<= temp.mtemp.i++) {
      if (
temp.s.charat(temp.i-1) == temp.t.charat(temp.j-1)) { 
        
temp.d[temp.i][temp.j] = temp.d[temp.i-1][temp.j-1];
      } else {
        
temp.d[temp.i][temp.j] = min(temp.d[temp.i-1][temp.j] + 1
                                    
min(temp.d[temp.i][temp.j-1] + 1temp.d[temp.i-1][temp.j-1] + 1)
                                    );
      }
    }
  }
  return 
temp.d[temp.m-1][temp.n-1];

e.x.,
PHP Code:
echo(levenshtein("kitten""sitting")); // echos 3
echo(levenshtein("Saturday""Sunday")); // echos 3
echo(levenshtein("unixmad""Stefan")); // echos 5 
Reply With Quote