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

Hide Tags

Dynamic Programming String

 

 
 
一个动态规划的题目,算是简单,不过开始考虑的不够完善。设一个二维数组a[i][j] 其中i 表示 word1 0 to i 字符串,i=0 的时候 表示“”,j 同理,那么a 中每项表示 i 字符串 转换到 j 字符串的最少步骤。
假如 我们已经知道了  <i-1,j-1>  <i-1,j> and  <i,j-1> 那么 <i,j>  可以如下求得:
  • word1[i] == word2[j] ,那么 可以看作 i-1 字符串 和 j-1 字符串各加了一个相同字符,所以<i,j> = <i-1,j-1>
  • word1[i] != word2[j]
    • 对于<i-1,j-1>,即两字符串后面都加了一个字符且不同,那么 replace 一次就行,所以<i,j> = <i-1,j-1>+1
    • 对于<i,j-1>,即只在 j-1 字符串后面加了一个字符,那么delete 一次就行,<i,j> = <i,j-1>+1
    • 对于<i-1,j>,同<i,j-1>
    • 所以 <i,j> 应该去上面3者最小值
  • 填满整个a 之后 <len1,len2> 为输出结果。

注意项:

  • a 二维数组需要考虑字符串为""的初始化,所以维度应该+1.
  • 我使用的是堆里面的空间,leetcode  可以直接使用栈空间创建,即不需要new。

我写的如下:

 #include <iostream>
#include <string>
#include <memory.h>
using namespace std; class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length(),len2=word2.length();
if(len1==) return len2;
if(len2==) return len1;
int **dpmap = new int *[len1+];
dpmap[] =new int[(len1+)*(len2+)];
memset(dpmap[],,sizeof(int)*(len1+)*(len2+));
for(int i= ;i<=len1;i++)
dpmap[i] = dpmap[i-]+len2+;
for(int i=;i<=len1;i++)
dpmap[i][] = i;
for(int j=;j<=len2;j++)
dpmap[][j] = j;
for(int i=;i<=len1;i++){
for(int j=;j<=len2;j++){
if(word1[i-]==word2[j-]) dpmap[i][j]=dpmap[i-][j-];
else{
dpmap[i][j]=(dpmap[i-][j]>dpmap[i][j-]?dpmap[i][j-]:dpmap[i-][j])+;
if(dpmap[i-][j-]+<dpmap[i][j])
dpmap[i][j] = dpmap[i-][j-]+;
}
}
}
int ret = dpmap[len1][len2];
// for(int i=0;i<=len1;i++){
// for(int j=0;j<=len2;j++)
// cout<<dpmap[i][j]<<" ";
// cout<<endl;
// }
delete []dpmap[];
delete []dpmap;
return ret;
}
}; int main()
{
string word1 = "";
string word2 = "";
Solution sol;
cout<<sol.minDistance(word1,word2)<<endl;
return ;
}

最新文章

  1. [systemtap手记]debian体系安装过程
  2. 给inpu加背景图,input内容又不能盖着背景图
  3. hdu5452 Minimum Cut
  4. linux基础-第六单元 用户、群组和权限
  5. (十) 一起学 Unix 环境高级编程 (APUE) 之 线程控制
  6. boost::bind 和 boost::function 基本用法
  7. mac terminal终端ls命令参数详解
  8. ssh连接失败解决方法
  9. Excel导入数据库(三)——SqlBulkCopy
  10. 原已经安装好的nginx,现在需要添加一个未被编译安装的模块--echo-nginx-module-0.56
  11. js清空页面控件值
  12. UI设计规范
  13. Java日志工具之java.util.logging.Logger
  14. zookeeper + dubbo + spring boot
  15. 探索Windows命令行系列(4):通过命令管理文件和文件夹
  16. [UnityShader基础]05.模板测试
  17. MySql与MariaDB由来与历程
  18. Httpclient的学习(一)
  19. 《DSP using MATLAB》Problem 6.23
  20. docker 报ls: cannot open directory software/: Permission denied

热门文章

  1. Nginx正向代理代理http和https服务
  2. 使用vs2013打开VS2015的工程文件的解决方案(适用于大多数vs低版本打开高版本)
  3. Node项目实战-静态资源服务器
  4. H5 JS判断客户端是否是iOS或者Android手机移动端
  5. DC课程目标
  6. 【mysql】mysql存储过程实例
  7. 2018 Python开发者大调查:Python和JavaScript最配?
  8. shutil,zipfile,tarfile模块
  9. Head First Python (二)
  10. [转] 彻底搞懂word-break、word-wrap、white-space