LeetCode#583-两个字符串的删除操作-求最大公共子序列

/*
给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。

 

示例:

输入: "sea", "eat"
输出: 2
解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"

    思路:找出最大公共子序列
          动态规划
 */
public class p583 {
    public static int minDistance(String word1, String word2) {
        int dp[][]=new int[word1.length()+1][word2.length()+1];
        for(int i=0;i<=word1.length()-1;i++)
            for(int j=0;j<=word2.length()-1;j++){
                if(word1.charAt(i)==word2.charAt(j)){
                    dp[i+1][j+1]=dp[i][j]+1;
                }
                else{
                    dp[i+1][j+1]=Math.max(dp[i][j+1],dp[i+1][j]);
                }

            }
        return  word1.length()+word2.length()-2*dp[word1.length()][word2.length()];

    }

    public static void main(String[] args) {
        System.out.println(minDistance("set","eat"));
    }
}

  运行结果:

原文地址:https://www.cnblogs.com/jifeng0902/p/13234795.html