第十三周:( LeetCode583) Delete Operation for Two Strings(c++)
来源:互联网 发布:java多线程售票系统 编辑:程序博客网 时间:2024/06/03 14:46
求字符串编辑距离的题,经典动态规划。
原题:
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: “sea”, “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
Note:
The length of given words won’t exceed 500.
Characters in given words can only be lower-case letters.
思路:
简单的字符串编辑距离变种。由于字符串只能有一种操作(删除)。所以实际上也就是求两个字符串最长相同子串(不要求连续,因为删除操作可以在任意位置)的长度。动态转移方程为:(1)word1[i]=word2[j],dp[i][j]=dp[i-1][j-1]+1(2)word[i]!=word[j],dp[i][j]=max(dp[i-1][j],dp[i][j-1])。时间复杂度为o(n^2)。
代码:
class Solution {public: int minDistance(string word1, string word2) { int n1=word1.length(),n2=word2.length(); int dp[n1+1][n2+1]; //i,j分别代表word1,word2的第i,j位的字符。i=0,j=0表示字符串为空 for(int i=0;i<=n1;i++){ for(int j=0;j<=n2;j++){ //初始化 if((i==0)||(j==0)) dp[i][j]=0; else{ if(word1[i-1]==word2[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return n1+n2-dp[n1][n2]*2; }};
1 0
- 第十三周:( LeetCode583) Delete Operation for Two Strings(c++)
- leetcode583. Delete Operation for Two Strings
- Delete Operation for Two Strings
- 算法第12周Delete Operation for Two Strings[Medium]
- 583. Delete Operation for Two Strings Medium
- [LeetCode]583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- [leetcode] 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 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
- 583.Delete Operation for Two Strings
- LeetCode:M-583. Delete Operation for Two Strings
- Delete Operation for Two Strings问题及解法
- Leetcode之Delete Operation for Two Strings 问题
- Android编程心得-使用Application类保存应用的全局数据
- 国际化乱码类型
- HTML CSS笔记
- 添加时间联系人添加两次,两次请求
- [LeetCode]501. Find Mode in Binary Search Tree
- 第十三周:( LeetCode583) Delete Operation for Two Strings(c++)
- 仿微信:Activity跟随手指滑动效果SlideFinishActivity
- Android开发之RecyclerView的基本使用(实现常用的4种效果)
- Fragment坑之Can not perform this action after onSaveInstanceState
- java虚拟机(一知半解)
- 数据结构——树形结构概念
- for循环的三种方式
- HDU 3951 Coin Game
- Apache-NiFi授权与用户认证