您的位置:首页 > 其它

LeetCode 72. Edit Distance(编辑距离)

2016-05-22 05:18 405 查看
原题网址: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];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: