Edit Distance
来源:互联网 发布:diagbox软件 编辑:程序博客网 时间:2024/04/25 08:33
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
解法:动态规划:对于串word1[1,i]和word2[1,j],如果word1[i]==word2[j],则距离等于两个字符串去掉最后一个字母的距离;如果不相等,有三种操作,word1去掉i,word1[1,i-1]和word2[1,j]比较;word2去掉j,word1[1,i]和word2[1,j-1]比较;word1[i]改成word2[j],word1[1,i-1]和word2[1,j-1]比较,都需要额外一步操作。
class Solution {public: int minDistance(string word1, string word2) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = word1.length(); int n = word2.length(); int dis[m+1][n+1]; for(int i = 0;i <= m;i++) dis[i][0] = i; for(int j = 0; j <= n;j++) dis[0][j] = j; for(int i = 1; i<= m;i++) { for(int j = 1;j<=n;j++) { if(word1[i-1] == word2[j-1]){ dis[i][j] = dis[i-1][j-1]; }else{ dis[i][j] = min(dis[i-1][j],dis[i][j-1])+1; dis[i][j] = min(dis[i][j],dis[i-1][j-1]+1); } } } return dis[m][n]; }};80 milli secs.
- edit distance
- Edit Distance
- edit distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- C++ Primer学习笔记2--c++标准库中的 vector、string 和 bitset 类型
- EXIF 方向参数 Orientation
- ANDROID.VIEW.INFLATEEXCEPTION解决方法
- 使Tomcat指向指定的JDK目录
- 实用数据结构之二叉排序树小结
- Edit Distance
- php 中 return exit break contiue 详解
- XCODE使用经验
- #define WINAPI __stdcall是什么意思(转)
- 【可爱美女杨紫桌面热门主题】
- grails 210-项目实战G
- C#网页自动登录和提交POST信息的多种方法
- Wc2008 游览计划(STNT + 输出路径)
- C++Primer中文版(第5版)(顶级畅销书重磅升级 全面采用最新 C++ 11标准)