Leetcode Edit Distance
2024-08-31 10:33:43
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];
}
};
最新文章
- 写给自己:修改配置文件一定要cp一个.bak
- [Java] Maven 安装和配置
- 解决 g++ error:/usr/lib/rpm/redhat/redhat-hardened-cc1 No that file and directory
- TCP/IP协议学习(一) LWIP实现网络远程IAP下载更新
- 《MORE EFFECTIVE C++》条款20 条款21
- poj2017
- 怎样在VS2013/MFC中使用TeeChart绘图控件
- PLSQL中便捷的输入
- Android中全局Application的onCreate多次调用问题
- Python(2.7.6) 标准日志模块的简单示例
- iOS工程中的info.plist文件
- Android开发了解——AAPT
- Python3 IO
- Filter简单介绍
- (C#)Windows Shell 编程系列2 - 解释,从“桌面”开始展开
- python模块介绍- xlwt 创建xls文件(excel)
- flask中的session,render_template()第二和参数是字典
- 微信小程序 组件 Demo
- Spring Batch(三) Job Launcher、ItemReader、ItemProcessor、ItemWriter各个实现类和用途
- Echarts3.0 引入百度地图(转载)
热门文章
- [译]学习HTTP协议的请求行
- hadoop源码编译——2.5.0版本
- undefined method `environment&#39; for nil:NilClass when importing Bootstrap into rails
- XHTML的规则
- 【Go入门教程4】struct类型(struct的匿名字段)
- 新语言代码高亮及Windows Live Writer插件开发
- HDU 5686 斐波那契数列、Java求大数
- jquery 事件委托
- Hadoop 部署过程中的一些问题与解决方案
- redmine问题集锦