博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Edit Distance
阅读量:4587 次
发布时间:2019-06-09

本文共 1554 字,大约阅读时间需要 5 分钟。

 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

思路:普通的DP很好写,问题是路径压缩的DP压缩如果进行,空间如何重复利用,和背包问题有点像,留待第二遍再解决

class Solution {public:    int minDistance(string word1, string word2) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int ** dp = new int*[word1.size() + 1];        for(int i = 0; i < word1.size() + 1; i++){            dp[i] = new int[word2.size() + 1];        }                for(int i = 0; i < word1.size() + 1; i++){            dp[i][0] = i;        }        for(int j = 0; j < word2.size() + 1; j++){            dp[0][j] = j;        }                for(int i = 1; i < word1.size() + 1; i++){            for(int j = 1; j < word2.size() + 1; j++){                if (word1[i-1] == word2[j-1]){                    //相等的情况下,最后一个元素不占用操作                    dp[i][j] = dp[i-1][j-1];                }else{                    //delete一种串                    dp[i][j] = min(dp[i-1][j] + 1,dp[i][j-1] + 1);                    //i和j的位置进行replace                    dp[i][j] = min(dp[i][j],dp[i-1][j-1] + 1);                }            }        }                    int ans = dp[word1.size()][word2.size()];        for(int i = 0; i < word1.size() + 1; i++){            delete []dp[i];        }        delete []dp;        return ans;    }};

 

转载于:https://www.cnblogs.com/kwill/p/3182882.html

你可能感兴趣的文章
mybatis中封装结果集常见示例
查看>>
FREESWITCH 填坑指南
查看>>
ASP Err.Number 对应的Description
查看>>
归并排序
查看>>
md5加密通过URL传给后台
查看>>
eclipse安装activiti工作流插件
查看>>
MySQL系列教程(一)
查看>>
面向对象设计七大原则
查看>>
React-Redux之connect
查看>>
ubuntu下如何卸载nvidia显卡驱动?
查看>>
tp框架支付宝手机网页支付
查看>>
【栈】【AOJ-558】窃取任务
查看>>
两个被混淆的单词property和attribute
查看>>
MySQL存储过程
查看>>
第四周作业
查看>>
VS2010安装包制作过程
查看>>
第十一周进度总结
查看>>
python机器学习——分词
查看>>
PHP5 mysqli 教程
查看>>
C#与Java 详细比较
查看>>