描述

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

思路:动态规划

这是一个经典的动态规划问题,思路参考斯坦福的课程:http://www.stanford.edu/class/cs124/lec/med.pdf

这里把加2变成加1即可

  1. dp[i][0] = i;
  2. dp[0][j] = j;
  3. dp[i][j] = dp[i - 1][j - 1], if word1[i - 1] = word2[j - 1];
  4. dp[i][j] = min(dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1, dp[i][j - 1] + 1), otherwise.
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
vector<vector<int> > dp(m+, vector<int>(n+, ));
for(int i = ;i<=m;++i)
dp[i][] = i;
for(int i = ;i<=n;++i)
dp[][i] = i;
for(int i = ;i<=m;++i){
for(int j = ;j<=n;++j){
if(word1[i-] == word2[j-])
dp[i][j] = dp[i-][j-];
else
dp[i][j] = min(dp[i-][j-], min(dp[i][j-], dp[i-][j])) + ;
}
}
return dp[m][n];
}
};

最新文章

  1. nginx切割日志
  2. Python操作memcached及redis
  3. iOS不得姐项目--登录模块的布局,设置文本框占位文字颜色,自定义内部控件竖直排列的按钮
  4. 转换 Html 内容为纯文本内容(html,文本互转)
  5. js电话号码正则校验--座机和手机号
  6. JIRA官方:JIRA亮点介绍
  7. 高性能JavaScript读书笔记
  8. Ameba读写分离_mycat分库分表_redis缓存
  9. BZOJ1095(动态点分治+堆)
  10. Owin学习笔记(二) 中间件开发
  11. Kafka动态增加Topic的副本
  12. GridView1 RowDataBound
  13. ExtJS获取Grid的行数
  14. monkey测试===Monkey测试策略(系列二)转
  15. CodeForces - 986A Fair (BFS+贪心)
  16. Problem V: 零起点学算法20——输出特殊值II
  17. Java_数据交换_JAXB_用法入门
  18. Git发布本地项目至仓库命令行操作流程
  19. unique within an element
  20. 移植MonkeyRunner的图片对照和获取子图功能的实现-UiAutomator/Robotium篇

热门文章

  1. Java联网技术之一TCP socket
  2. SparseArray具体解释,我说SparseArray,你说要!
  3. MySQL同步状态双Yes的假象及 seconds_behind_master的含义
  4. grails 获取domainClassName
  5. 【Mac + Appium + Python3.6学习(三)】之IOS自动化测试环境配置
  6. PHP中插件机制的一种实现方案
  7. windows中控制台窗口和普通窗口有什么区别?
  8. JEECMS 2.4.2 之添加新的可扩展的ftl模版文件、自定义方法
  9. Codeforces 460 D. Little Victor and Set
  10. Android Studio3.0 配置ButterKnife出错的解决