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

输入两个单词word1和word2,求出从word1转换成word2的最少步骤。每个转换操作算一步。转换操作限定于:

  • 删除一个字符
  • 插入一个字符
  • 替换一个字符

本题用动态规划求解

设决策变量dp[i][j],表示从word[0..i-1]转换为word2[0...j-1]的最少步骤

可以参考http://web.stanford.edu/class/cs124/lec/med.pdf

class Solution {
public:
int minDistance(string word1, string word2) {
int len1 =word1.length(), len2 = word2.length();
if(len1 == ) return len2;
if(len2 == ) return len1;
if(word1 == word2) return ;
vector<vector<int> > dp(len1+, vector<int>(len2+,));
for(int i = ; i <= len1; ++ i) dp[i][] = i;
for(int j = ; j <= len2; ++ j) dp[][j] = j;
for(int i =; i <= len1; ++ i){
for(int j = ; j <= len2; ++ j){
dp[i][j] = min(dp[i-][j-]+(word1[i-] != word2[j-]? : ),min(dp[i-][j]+, dp[i][j-]+));
}
}
return dp[len1][len2];
}
};

最新文章

  1. 写给自己:修改配置文件一定要cp一个.bak
  2. [Java] Maven 安装和配置
  3. 解决 g++ error:/usr/lib/rpm/redhat/redhat-hardened-cc1 No that file and directory
  4. TCP/IP协议学习(一) LWIP实现网络远程IAP下载更新
  5. 《MORE EFFECTIVE C++》条款20 条款21
  6. poj2017
  7. 怎样在VS2013/MFC中使用TeeChart绘图控件
  8. PLSQL中便捷的输入
  9. Android中全局Application的onCreate多次调用问题
  10. Python(2.7.6) 标准日志模块的简单示例
  11. iOS工程中的info.plist文件
  12. Android开发了解——AAPT
  13. Python3 IO
  14. Filter简单介绍
  15. (C#)Windows Shell 编程系列2 - 解释,从“桌面”开始展开
  16. python模块介绍- xlwt 创建xls文件(excel)
  17. flask中的session,render_template()第二和参数是字典
  18. 微信小程序 组件 Demo
  19. Spring Batch(三) Job Launcher、ItemReader、ItemProcessor、ItemWriter各个实现类和用途
  20. Echarts3.0 引入百度地图(转载)

热门文章

  1. [译]学习HTTP协议的请求行
  2. hadoop源码编译——2.5.0版本
  3. undefined method `environment&#39; for nil:NilClass when importing Bootstrap into rails
  4. XHTML的规则
  5. 【Go入门教程4】struct类型(struct的匿名字段)
  6. 新语言代码高亮及Windows Live Writer插件开发
  7. HDU 5686 斐波那契数列、Java求大数
  8. jquery 事件委托
  9. Hadoop 部署过程中的一些问题与解决方案
  10. redmine问题集锦