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
public class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
if(m==0) return n;
if(n==0) return m;
int edit[][] = new int[m+1][n+1];
for(int i=0;i<=m;i++) {
edit[i][0] = i;
}
for(int i=0;i<=n;i++) {
edit[0][i] = i;
}
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(word1.charAt(i)==word2.charAt(j)) {
edit[i+1][j+1] = edit[i][j];
} else {
edit[i+1][j+1] = 1 + Math.min(edit[i][j], Math.min(edit[i+1][j], edit[i][j+1]));
}
}
}
return edit[m][n];
}
}
=========
public class Solution {
public int minDistance(String word1, String word2) {
int[][] edit = new int[word1.length() + 1][word2.length() + 1];
for (int i = 0; i <= word1.length(); i++) {
for (int j = 0; j <= word2.length(); j++) {
if (i == 0) {
edit[i][j] = j;
} else if (j == 0) {
edit[i][j] = i;
} else if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
edit[i][j] = edit[i - 1][j - 1];
} else {
edit[i][j] = Math.min(Math.min(edit[i][j - 1], edit[i - 1][j]), edit[i - 1][j - 1]) + 1;
}
}
}
return edit[word1.length()][word2.length()];
}
}
没有评论:
发表评论