您的位置:首页 > 其它

*Edit Distance

2015-09-25 11:37 337 查看
题目:

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:

Insert a character

Delete a character

Replace a character

Example

Given word1 =
"mart"
and word2 =
"karma"
, return
3
.





/**
* 本代码由九章算法编辑提供。没有版权欢迎转发。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
* - 更多详情请见官方网站:http://www.jiuzhang.com/
*/

public class Solution {
public int minDistance(String word1, String word2) {
int n = word1.length();
int m = word2.length();

int[][] dp = new int[n+1][m+1];
for(int i=0; i< m+1; i++){
dp[0][i] = i;
}
for(int i=0; i<n+1; i++){
dp[i][0] = i;
}

for(int i = 1; i<n+1; i++){
for(int j=1; j<m+1; j++){
if(word1.charAt(i-1) == word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]));
}
}
}
return dp
[m];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: