动态规划——72. Edit Distance[HARD]
来源:互联网 发布:linux怎么修改文件权限 编辑:程序博客网 时间:2024/06/05 11:35
题目描述
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
解题思路
1)dp[i][j]:word1 0~i 和 word2 0~j 的编辑距离。
2)考虑word1[i] word2[j]的对齐方式:
注意因为出现 i-1,j-1,所以要考虑数组越界问题,因此多生成0行和0列,对应某一个str为空时的情况
代码如下
class Solution {public: int minDistance(string word1, string word2) {if (word1.empty() && word2.empty())return 0;if (word1.empty())return word2.size();if (word2.empty())return word1.size();vector<int> tmp(word2.size()+1, 0);vector<vector<int> > dp(word1.size()+1, tmp);for (int i = 0; i <= word2.size(); i++)dp[0][i] = i;for (int j = 0; j <= word1.size(); j++)dp[j][0] = j;for (int i = 1; i <= word1.size(); i++) {for (int j = 1; j <= word2.size(); j++) {int op = (word1[i-1] == word2[j-1] )? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1;dp[i][j] = fmin(dp[i - 1][j] + 1, fmin(dp[i][j - 1] + 1, op));}}return dp[word1.size()][word2.size()];}};
阅读全文
0 0
- 动态规划——72. Edit Distance[HARD]
- 13.9—动态规划—Edit Distance
- 72. Edit Distance Hard
- Edit Distance 动态规划
- 72. Edit Distance 动态规划dp
- LeetCode----72. Edit Distance(H) 动态规划
- 行编辑距离Edit Distance——动态规划
- 【哈希、动态规划】Edit Distance
- LeetCode Edit Distance(动态规划)
- LeetCode刷题(C++)——Edit Distance(Hard)
- 算法学习之动态规划(leetcode 72. Edit Distance)
- 72. Edit Distance(动态规划中二维降一维)
- leetcode 72. Edit Distance DP动态规划 + 编辑距离
- Hard-题目13:72. Edit Distance
- (Leetcode)72. Edit Distance(hard)
- Leetcode 72. Edit Distance (Hard) (cpp)
- Edit Distance----hard
- 动态规划——edit-distance 计算字符串的相似度
- ConcurrentLinkedQueue
- 机器学习-周志华-个人练习13.1
- 使用endnote在word中插入参考文献
- 【Redis学习】:hash数据类型详解
- 2017年五月二十九日 NO.3 HTML(二)——基本文档元素(笔记)
- 动态规划——72. Edit Distance[HARD]
- 【Redis学习】:list数据类型详解
- pytorch-fineturn the network and adjust learning rate
- 数据结构(图--邻接矩阵法实现)
- 【Redis学习】:set数据类型详解
- 旧版漏洞 Bug 被发现可致 Win7/8.1 “崩溃”
- 数据库连接池
- python3 类的学习
- (179)编辑材质函数