Edit Distance(两字符串经过最少操作匹配)
2016-04-07 09:28
204 查看
72. Edit Distance
My SubmissionsQuestion
Editorial Solution
Total Accepted: 55602 Total
Submissions: 195784 Difficulty: Hard
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
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
显然采用动态规划做:
用dp[n+1][m+1]表示需要执行的最少变换次数,则递推方程为:
dp[i+1][j+1] = dp[i][j], 当word1[i] == word2[j]
dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1); 当word1[i] != word2[j]
class Solution { public: int minDistance(string word1, string word2) { int len1 = word1.size(), len2 = word2.size(); vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1)); // 左边沿初始化 for (int i = 0; i <= len1; ++i) dp[i][0] = i; // 右边沿初始化 for (int i = 0; i <= len2; ++i) dp[0][i] = i; for (int i = 0; i < len1; ++i) { for (int j = 0; j < len2; ++j) { if (word1[i] == word2[j]) dp[i + 1][j + 1] = dp[i][j]; else dp[i + 1][j + 1] = min(min(dp[i][j] + 1, dp[i][j + 1] + 1), dp[i + 1][j] + 1); } } return dp[len1][len2]; } };
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析