[LeeCode]Edit Distance
来源:互联网 发布:电脑版数据恢复精灵 编辑:程序博客网 时间:2024/05/21 06:55
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
- 如何分析一个产品?
- 10条HTML容易出错的转义符
- 如何在线打开word文档并高亮显示指定关键字
- Ubuntu 下rename 命令的使用
- echo(),print(),print_r()的区别
- [LeeCode]Edit Distance
- ip地址
- POJ 2676 Sudoku
- Android之@Override详解
- JSP标准标签库 通用标签
- 带有事务的存储过程的写法
- 还在为电脑反应慢惆怅么?现在教你怎么为电脑'减肥'!
- android启动模式
- js验证身份证号码(包括与用户输入性别,生日的匹配性验证)