Skip to content

Instantly share code, notes, and snippets.

@t11a
Last active August 29, 2015 13:57
Show Gist options
  • Save t11a/9763862 to your computer and use it in GitHub Desktop.
Save t11a/9763862 to your computer and use it in GitHub Desktop.
Levenshtein distance
#include <iostream>
#include <string>
#define FOR(i,m,n) for (int i=(m); i<(int)(n) ;i++)
int main() {
string x = "google";
string y = "gooogle";
int size_x = x.length();
int size_y = y.length();
int dp[size_x+1][size_y+1];
FOR(i,0,size_x+1)
FOR(j,0,size_y+1)
dp[i][j] = 0;
FOR(i,0,size_x+1) dp[i][0] = i;
FOR(i,0,size_y+1) dp[0][i] = i;
FOR(i,1,size_x+1) {
FOR(j,1,size_y+1) {
int cost;
if (x[i-1] == y[j-1]) cost=0;
else cost = 1;
dp[i][j] = dp[i-1][j]+1; // insert
dp[i][j] = min(dp[i][j], dp[i][j-1]+1); // delete
dp[i][j] = min(dp[i][j], dp[i-1][j-1]+cost); // swap
}
}
FOR(i,0,size_x+1) {
FOR(j,0,size_y+1) {
cout << dp[i][j] << ' ';
}
cout << endl;
}
cout << dp[size_x][size_y] << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment