Skip to content

Instantly share code, notes, and snippets.

@ianpark
Created May 25, 2015 16:17
Show Gist options
  • Save ianpark/5b1c9ed48ee2ff4a2f3e to your computer and use it in GitHub Desktop.
Save ianpark/5b1c9ed48ee2ff4a2f3e to your computer and use it in GitHub Desktop.
C++ implementation of Edit Distance Algorithm
size_t edit_distance(const string& A, const string& B)
{
size_t NA = A.size();
size_t NB = B.size();
vector<vector<size_t>> M(NA + 1, vector<size_t>(NB + 1));
for (size_t i = 0; i <= NA; ++i)
M[i][0] = i;
for (size_t i = 0; i <= NB; ++i)
M[0][i] = i;
for (size_t a = 1; a <= NA; ++a)
for (size_t b = 1; b <= NB; ++b)
{
size_t x = M[a - 1][b] + 1;
size_t y = M[a][b - 1] + 1;
size_t z = M[a - 1][b - 1] + (A[a - 1] == B[b - 1] ? 0 : 1);
M[a][b] = min(x, y, z);
}
return M[A.size()][B.size()];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment