[LeetCode OJ]Edit Distance
来源:互联网 发布:求对数据入门分析 编辑:程序博客网 时间:2024/06/04 18:48
【问题描述】
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
问题来源:Edit Distance
【解题分析】
我们的目标是寻找两个字符串x[1...m]与y[1...n]之间的编辑距离。试着考虑一下这两个字符串的前缀x[1...i]与y[1...j]之间的编辑距离,将该问题记为E(i,j)。来看一下关于x[1...i]与y[1...j]之间的最佳对齐,显然,该对齐中最右侧的列只可能为如下三种情况之一:
第一种情况产生的代价为1,余下的则是E(i-1,j)之间的对齐问题;第二种情况产生的代价为1,余下的则是E(i,j-1)之间的对齐问题;第三种情况的代价则是differ(x[i],y[j]),如果x[i]=y[j],则代价为0,否则代价为1,余下的则是E(i-1,j-1)之间的对齐问题。
E(i,j) = min{1+E(i-1,j), 1+E(i,j-1),differ(x[i],y[j])+E(i-1,j-1)}
时间复杂度O(mn),空间复杂度为O(mn)。
【源代码】
class Solution {public:int minDistance(string word1, string word2) {int m = word1.size();int n = word2.size();vector<vector<int> > dp(m+1, vector<int>(n+1, 0));for (int i = 1; i <= m; i++) {dp[i][0] = i;}for (int j = 1; j <= n; j++) {dp[0][j] = j;}for (int i = 1; i <= m; i++) {for (int j = 1; j <= n; j++) {if (word1[i-1] == word2[j-1]) {dp[i][j] = dp[i-1][j-1];} else {dp[i][j] = min(1+dp[i-1][j], min(1+dp[i][j-1], 1+dp[i-1][j-1]));}}}return dp[m][n];}};
阅读全文
0 0
- LeetCode OJ:Edit Distance
- LeetCode OJ - Edit Distance
- LeetCode OJ Edit Distance
- LeetCode OJ - - Edit Distance
- [LeetCode OJ]Edit Distance
- OJ 72 Edit Distance
- LeetCode OJ算法题(七十二):Edit Distance
- LeetCode OJ 之 Edit Distance (编辑距离)
- LeetCode: Edit Distance
- LeetCode Edit Distance
- LeetCode: Edit Distance
- [Leetcode] Edit Distance
- leetcode 19: Edit Distance
- [LeetCode] Edit Distance
- [Leetcode] Edit Distance
- LeetCode Edit Distance
- [LeetCode] Edit Distance
- [LeetCode]Edit Distance
- 小程序与php 实现微信支付
- AP ---(Wireless Access Point) 研究
- 停车管理系统
- ThinkPHP微信JSSDK的使用
- linux 快速获得版本地址
- [LeetCode OJ]Edit Distance
- 闭锁 CountDownLatch
- java通用程序设计建议(二)
- 桌面版和服务器版的升级办法ubuntu13.04------ ubuntu13.10
- xxx 用户不再sudoer 文件中 此事将被报告。
- CentOS桌面yum安装Adobe Flash Player
- vs2015 将项目做成DLL的几个要注意的步骤
- 如何在 CentOS 6.4为 Firefox 设置 x86_64 的插件
- vim 配置