[LeetCode]583. Delete Operation for Two Strings
来源:互联网 发布:辐射4低配置优化 编辑:程序博客网 时间:2024/06/05 22:52
[LeetCode]583. Delete Operation for Two Strings
题目描述
思路
动态规划
实际上是找最长公共子序列
建立一个二维数组,dp[i][j]保存到word1第i位和word2第j位时最长公共的子序列的长度
更新方式详见代码
代码
#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;class Solution {public: int minDistace(string word1, string word2) { if (word1.size() == 0 || word2.size() == 0) return word1.size() + word2.size(); vector<vector<int>> dp(word1.size(), vector<int>(word2.size())); for (int i = 0; i < word1.size(); ++i) { for (int j = 0; j < word2.size(); ++j) { if (i == 0 && j == 0) dp[i][j] = word1[i] == word2[j]; else if (i == 0) dp[i][j] = word1[i] == word2[j] ? 1 : dp[i][j - 1]; else if (j == 0) dp[i][j] = word1[i] == word2[j] ? 1 : dp[i - 1][j]; else dp[i][j] = word1[i] == word2[j] ? dp[i - 1][j - 1] + 1 : max(max(dp[i - 1][j], dp[i - 1][j - 1]), dp[i][j - 1]); } } return word1.size() + word2.size() - (dp[word1.size() - 1][word2.size() - 1] << 1); }};int main() { Solution s; cout << s.minDistace("aaa", "ababa") << endl; system("pause"); return 0;}
阅读全文
0 0
- [LeetCode]583. Delete Operation for Two Strings
- [leetcode] 583. Delete Operation for Two Strings
- [leetcode]583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings
- [LeetCode] 583. Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- LeetCode:M-583. Delete Operation for Two Strings
- #leetcode编程日记#583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings Medium
- 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 583.Delete Operation for Two Strings
- Delete Operation for Two Strings
- Leetcode之Delete Operation for Two Strings 问题
- 【Leetcode-Medium-583】Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings 最长公共子串 + DP动态规划
- leetcode583. Delete Operation for Two Strings
- js中的参数传递
- [LeetCode]20.Valid Parentheses
- 蓝桥杯决赛之魔方
- 算法训练 红与黑
- 下拉框默认选中当前年、月、日的实现!
- [LeetCode]583. Delete Operation for Two Strings
- 复习
- HTML的基本结构语法
- codeigniter3项目实践,项目目录和公共配置文件
- java并发编程(一)-并发编程需要注意问题
- vs 2012 使用IIS Express 64位调试
- MSP430 BootLoader移植
- Android开发中,让你事半功倍的整理归档(二)
- DNS服务器的配置与管理