Question

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

Solution

动态规划。参见以前的博客:http://www.cnblogs.com/zhonghuasong/p/6147030.html

Code

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

最新文章

  1. sikuli实战记录
  2. jQuery实现滚动效果详解1
  3. 在Linux下用源码编译安装apache2
  4. 避免HTML5六种错误用法
  5. mini2440裸机之MMU(二)(mmu.c) (转)
  6. 使用vi是方向键变乱码 退格键不能使用的解决方法
  7. 赵雅智_ListView_BaseAdapter
  8. ASP.NET Core MVC 源码学习:详解 Action 的激活
  9. vxworks下文件读写示例
  10. linux-----docker
  11. [Codeforces741D]Arpa&#39;s letter-marked tree and Mehrdad&#39;s Dokhtar-kosh paths——dsu on tree
  12. hdu3746 Cyclic Nacklace KMP
  13. shell脚本判断执行用户
  14. 利用ListView批量删除item
  15. XenServer:使用XenCenter开设VPS(多图完整版)
  16. CentOS 7.3 CDH 5.10.0 Druid0.12.4安装记录
  17. 项目总结--基于Cortex-A9平台的米兰花智能培育系统
  18. 外国人专门写了一篇文章,来分析为什么go在中国如此火
  19. python之django直接执行sql语句
  20. 【转】性能测试工具JMeter的使用技巧

热门文章

  1. activate mod_rewrite How To Set Up mod_rewrite for Apache on Ubuntu 14.04 Apache Rewrite url重定向功能的简单配置
  2. Logstash利用GeoIP库显示地图以及通过useragent显示浏览器(
  3. 剑指Offer——二叉搜索树的第k个结点
  4. Linux上安装Zabbix客户端
  5. apache2.2版本 configuration error: couldn&#39;t perform authentication. AuthType not set!: /
  6. nginx.conf常用配置解析
  7. mysql数据池设置
  8. Secure Sockets Layer(安全套接层)
  9. XSS注入学习
  10. javaScript动画2 scroll家族