[LeetCode]Edit Distance
2015-11-26 15:36
676 查看
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
动态规划。f(i,j)代表 word1 前i位 和 word2 前 j位 转换时最小的次数。
分两种情况,如果word1[i] == word2 [j]:
i位和j位相等,说明 f(i,j) = f(i-1,j-1).没有cost
如果word1[i] 和 word2[j] 不相等,分三种情况:
删除 f(i-1,j) 替换 f(i-1,j-1)
插入 f(i,j-1) f(i,j) = min(f(i-1,j),f(i-1,j-1),f(i,j-1))+1;
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
动态规划。f(i,j)代表 word1 前i位 和 word2 前 j位 转换时最小的次数。
分两种情况,如果word1[i] == word2 [j]:
i位和j位相等,说明 f(i,j) = f(i-1,j-1).没有cost
如果word1[i] 和 word2[j] 不相等,分三种情况:
删除 f(i-1,j) 替换 f(i-1,j-1)
插入 f(i,j-1) f(i,j) = min(f(i-1,j),f(i-1,j-1),f(i,j-1))+1;
class Solution { public: int minDistance(string word1, string word2) { int len1 = word1.size(); int len2 = word2.size(); if(len1==0) return len2; if(len2==0) return len1; vector<vector<int>> Dp (len1+1,vector<int>(len2+1,0)) ; for(int i=0; i<len1+1; ++i){ Dp[i][0] = i; } for(int i=0; i<len2+1; ++i){ Dp[0][i] = i; } for(int i=1; i<len1+1; ++i){ for(int j=1; j<len2+1; ++j){ if(word1[i-1] == word2[j-1]){ Dp[i][j] = Dp[i-1][j-1]; } else{ Dp[i][j] = 1+min(Dp[i-1][j-1],Dp[i-1][j],Dp[i][j-1]); } } } return Dp[len1][len2]; } int min(int a,int b, int c){ int min = a; if(min>b) min = b; if(min>c) min = c; return min; } };
相关文章推荐
- Geometry类详解
- 【技♂巧】bzoj1257余数之和
- 实现多国语言的几个小知识
- swift可选链和类型转换
- 【学习笔记】分区表和分区索引——概念部分(一)
- [python]python子字符串的提取、字符串连接、字符串重复
- oracle function学习1
- 模拟迁途箭头圆圈
- ubuntu下创建、删除文件、文件夹,移动文件
- css层叠样式详解
- android View各属性详解
- 二叉搜索树-BST-查找算法-插入算法-删除算法 http://www.cnblogs.com/pangxiaodong/archive/2011/08/24/2151060.html
- 模拟迁途.html
- windows server做NTP时间服务器 及时间设置internet时间同步的方法
- 【实战Java高并发程序设计 2】无锁的对象引用:AtomicReference
- OSSIM下安装phpadmin全过程
- Java的Struts框架中Action的编写与拦截器的使用方法
- PHP在foreach中对$value赋值无效的问题
- BOW模型在ANN框架下的解释
- MySQL表结构修改