Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:19
Show Gist options
  • Save HDegano/3dd8f6e782e310cf2483 to your computer and use it in GitHub Desktop.
Save HDegano/3dd8f6e782e310cf2483 to your computer and use it in GitHub Desktop.
Given two strings, return the min edit distance
/*
Requires O(mn) space
*/
public class Solution {
public int MinDistance(string word1, string word2) {
int[,] dp = new int[word2.Length + 1, word1.Length + 1];
for (int i = 0; i <= word1.Length; i++) dp[0, i] = i;
for (int i = 0; i <= word2.Length; i++) dp[i, 0] = i;
for (int i = 1; i < word2.Length + 1; i++)
for (int j = 1; j < word1.Length + 1; j++){
if (word1[j - 1] == word2[i - 1])
dp[i, j] = dp[i - 1, j - 1];
else
{
dp[i, j] = getMin(dp[i - 1, j], dp[i, j - 1], dp[i - 1, j - 1]) + 1;
}
}
return dp[word2.Length, word1.Length];
}
private int getMin(int a, int b, int c)
{
var less = a < b ? a : b;
return less < c ? less : c;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment