Skip to content

Instantly share code, notes, and snippets.

@fever324
Created November 12, 2014 04:01
Show Gist options
  • Save fever324/317b27bb5067dfbd85f0 to your computer and use it in GitHub Desktop.
Save fever324/317b27bb5067dfbd85f0 to your computer and use it in GitHub Desktop.
Edit Distance
/*
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
*/
/* Dynamic Programming
Example. abcee vs abddd
0 | a | b | c | e | e
0| 0 1 2 3 4 5
a| 1 0 1 2 3 4
b| 2 1 0 1 2 3
d| 3 2 1 1 2 3
d| 4 3 2 2 2 3
d| 5 4 3 3 3 3
*/
public class Solution {
public int minDistance(String word1, String word2) {
int[][] a = new int[word1.length()+1][word2.length()+1];
for(int i = 0; i < word1.length()+1; i++) {
a[i][0] = i;
}
for(int j = 0; j < word2.length()+1; j++) {
a[0][j] = j;
}
for(int j = 1 ; j < word2.length() + 1; j++) {
for(int i = 1; i < word1.length() + 1; i++) {
if(word1.charAt(i-1) == word2.charAt(j-1)){
a[i][j] = a[i-1][j-1];
} else {
a[i][j] = Math.min(a[i-1][j-1], Math.min(a[i-1][j],a[i][j-1])) + 1;
}
}
}
return a[word1.length()][word2.length()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment