【LeetCode】【动态规划】Edit Distance
2024-08-26 02:36:37
描述
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:
- Insert a character
- Delete a character
- 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即可
dp[i][0] = i
;dp[0][j] = j
;dp[i][j] = dp[i - 1][j - 1]
, ifword1[i - 1] = word2[j - 1]
;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];
}
};
最新文章
- nginx切割日志
- Python操作memcached及redis
- iOS不得姐项目--登录模块的布局,设置文本框占位文字颜色,自定义内部控件竖直排列的按钮
- 转换 Html 内容为纯文本内容(html,文本互转)
- js电话号码正则校验--座机和手机号
- JIRA官方:JIRA亮点介绍
- 高性能JavaScript读书笔记
- Ameba读写分离_mycat分库分表_redis缓存
- BZOJ1095(动态点分治+堆)
- Owin学习笔记(二) 中间件开发
- Kafka动态增加Topic的副本
- GridView1 RowDataBound
- ExtJS获取Grid的行数
- monkey测试===Monkey测试策略(系列二)转
- CodeForces - 986A Fair (BFS+贪心)
- Problem V: 零起点学算法20——输出特殊值II
- Java_数据交换_JAXB_用法入门
- Git发布本地项目至仓库命令行操作流程
- unique within an element
- 移植MonkeyRunner的图片对照和获取子图功能的实现-UiAutomator/Robotium篇
热门文章
- Java联网技术之一TCP socket
- SparseArray具体解释,我说SparseArray,你说要!
- MySQL同步状态双Yes的假象及 seconds_behind_master的含义
- grails 获取domainClassName
- 【Mac + Appium + Python3.6学习(三)】之IOS自动化测试环境配置
- PHP中插件机制的一种实现方案
- windows中控制台窗口和普通窗口有什么区别?
- JEECMS 2.4.2 之添加新的可扩展的ftl模版文件、自定义方法
- Codeforces 460 D. Little Victor and Set
- Android Studio3.0 配置ButterKnife出错的解决