LeeCode]Edit Distance
来源:互联网 发布:毕业设计node.js 编辑:程序博客网 时间:2024/05/23 16:22
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
经典DP ,引wiki:
d[i, j] := 最小值( d[i-1, j ] + 1, // 刪除 d[i , j-1] + 1, // 插入 d[i-1, j-1] + cost // 替換若 str1[i] = str2[j] 則 cost := 0 否則 cost := 1)
编程之美上也有详细阐述,算法导论习题。
代码如下:
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- int len1 = word1.size();
- int len2 = word2.size();
- if(len1==0)
- return len2;
- if(len2==0)
- return len1;
- vector <vecotr <int> > f(len1+1,vector<int>(len2+1));
- for(int i = 0 ; i <= len1 ; i++)
- f[i][0] = i;
- for(int j =0 ; j <= len2 ; j++)
- f[0][j] = j;
- for(int i = 1 ; i<= len1 ; i++)
- for(int j = 1; j<= len2 ; j++)
- {
- int cost = 1;
- if(word1[i-1]==word2[j-1])
- cost =0;
- f[i][j] = min(f[i-1][j-1]+cost,min(f[i][j-1]+1, f[i-1][j]+1));
- }
- return f[len1][len2];
- }
- };
- [LeeCode]Edit Distance
- LeeCode]Edit Distance
- leecode 解题总结:72. 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
- HDOJ 2084 数塔问题
- deadline-iosched.txt
- 黑马程序员---基础语法(三)
- JavaScript类的点点滴滴
- c++primer第六版第七章第二题问题总结
- LeeCode]Edit Distance
- 我的Linux书架
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- 插入排序 Java/C++
- OCP-1Z0-053-V12.02-547题
- 一个应届计算机毕业生的2012求职之路
- adb shell 命令详解
- HDU 4770 Lights Against Dudely(枚举子集,简单模拟)
- 重温sunxin的VC++深入详解笔记(一)