原题网址:https://leetcode.com/problems/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
方法一:动态规划。
public class Solution {
public int minDistance(String word1, String word2) {
char[] wa1 = word1.toCharArray();
char[] wa2 = word2.toCharArray();
int[][] distance = new int[wa1.length+1][wa2.length+1];
for(int len2=1; len2<=wa2.length; len2++) distance[0][len2] = len2;
for(int len1=1; len1<=wa1.length; len1++) {
distance[len1][0] = len1;
for(int len2=1; len2<=wa2.length; len2++) {
if (wa2[len2-1] == wa1[len1-1]) distance[len1][len2] = distance[len1-1][len2-1];
else distance[len1][len2] = Math.min(distance[len1-1][len2-1], Math.min(distance[len1][len2-1], distance[len1-1][len2])) + 1;
}
}
return distance[wa1.length][wa2.length];
}
}
方法二:动态规划,优化内存。
public class Solution {
public int minDistance(String word1, String word2) {
char[] wa1 = word1.toCharArray();
char[] wa2 = word2.toCharArray();
int[] distance = new int[wa2.length+1];
int[] buf = new int[wa2.length+1];
for(int len2=0; len2<=wa2.length; len2++) distance[len2] = len2;
for(int len1=1; len1<=wa1.length; len1++) {
int[] prev = distance;
distance = buf;
distance[0] = len1;
for(int len2=1; len2<=wa2.length; len2++) {
if (wa1[len1-1] == wa2[len2-1]) distance[len2] = prev[len2-1];
else distance[len2] = Math.min(prev[len2-1], Math.min(distance[len2-1], prev[len2])) + 1;
}
buf = prev;
}
return distance[wa2.length];
}
}
方法三:递归+记忆化搜索。
public class Solution {
int[][] dist;
boolean[][] visit;
public int minDistance(String word1, String word2) {
if (visit == null) {
visit = new boolean[word1.length() + 1][word2.length() + 1];
dist = new int[word1.length() + 1][word2.length() + 1];
}
if (visit[word1.length()][word2.length()]) return dist[word1.length()][word2.length()];
if (word1.length() == 0) return word2.length();
if (word2.length() == 0) return word1.length();
if (word1.charAt(word1.length() - 1) == word2.charAt(word2.length() - 1)) {
dist[word1.length()][word2.length()] =
minDistance(word1.substring(0, word1.length() - 1), word2.substring(0, word2.length() - 1));
} else {
dist[word1.length()][word2.length()] = Math.min(
minDistance(word1.substring(0, word1.length() - 1), word2),
minDistance(word1, word2.substring(0, word2.length() - 1)));
dist[word1.length()][word2.length()] = Math.min(
dist[word1.length()][word2.length()],
minDistance(word1.substring(0, word1.length() - 1), word2.substring(0, word2.length() - 1)));
dist[word1.length()][word2.length()]++;
}
visit[word1.length()][word2.length()] = true;
return dist[word1.length()][word2.length()];
}
}