第十三周:( 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