*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 =
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]; } }
相关文章推荐
- android中Handle类的用法实例分析
- ASP.NET预备知识学习笔记
- android 混淆打包
- 数学中竟然还有这样的定理!
- PHP多线程读写文件操作
- 纯属记录下
- MyBatis返回值
- PowerShell 4.0实现自动化设置服务器
- 关于”图书管理系统(Borrowers,ACM/ICPC World Finals 1994, UVa230)"的讨论
- 数值的整数次方
- Redmine下载安装配置
- 计数排序
- iOS汉字转拼音
- Css3学习之路,画公司的Logo
- JQuery 无插件实现seclet option标签的拖拽放置
- NULL和nullptr
- JSF入门实例分析
- 35-算奖金
- 使用type=file 上传文件时2007后各文档如docx需配置的accept属性值
- Android - 线程同步