[LeetCode] Edit Distance 字符串变换为另一字符串动态规划
2024-09-08 15:52: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
Hide Tags
一个动态规划的题目,算是简单,不过开始考虑的不够完善。设一个二维数组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 ;
}
最新文章
- [systemtap手记]debian体系安装过程
- 给inpu加背景图,input内容又不能盖着背景图
- hdu5452 Minimum Cut
- linux基础-第六单元 用户、群组和权限
- (十) 一起学 Unix 环境高级编程 (APUE) 之 线程控制
- boost::bind 和 boost::function 基本用法
- mac terminal终端ls命令参数详解
- ssh连接失败解决方法
- Excel导入数据库(三)——SqlBulkCopy
- 原已经安装好的nginx,现在需要添加一个未被编译安装的模块--echo-nginx-module-0.56
- js清空页面控件值
- UI设计规范
- Java日志工具之java.util.logging.Logger
- zookeeper + dubbo + spring boot
- 探索Windows命令行系列(4):通过命令管理文件和文件夹
- [UnityShader基础]05.模板测试
- MySql与MariaDB由来与历程
- Httpclient的学习(一)
- 《DSP using MATLAB》Problem 6.23
- docker 报ls: cannot open directory software/: Permission denied