Longest Common Subsequence

来源:互联网 发布:matalab y引入数据 编辑:程序博客网 时间:2024/05/01 13:55

Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

Clarification

What's the definition of Longest Common Subsequence?

  • https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  • http://baike.baidu.com/view/2020307.htm
Example

For "ABCD" and "EDCA", the LCS is "A" (or "D""C"), return 1.

For "ABCD" and "EACB", the LCS is "AC", return 2.


最长公共子串问题,终于在OJ上碰到了。结果发现并不是很难。搞清楚状态转移方程就好。

首先构建一个二维的DP矩阵,然后初始化第一行第一列为0(好吧其实本身就是0所以不用管它)。

转移方程有两种情况:

1.  A.charAt(i) == B.charAt(j) .说明在A的0~i 位, 跟B的0~j 位, 有dp[i-1][j-1] + 1位是公共的。因为二者相等,所以要找到比当前小的规模的最优解,也就是dp[i-1][j-1]这个的值,它表示A的0~i-1 B的0~j-1位的最长公共子序列,然后在加上当前位相同。

2. 如果不相同的话,那么就从左边或者上边选择大的,因为最大值肯定只会出现在这两个方向。不走对角线的原因是,状态转移方程决定了这个值一定是大于或者等于对角线的值。我觉得这里还需要进一步说明,以后补上。


代码:

public int longestCommonSubsequence(String A, String B) {        // write your code here        if(A == null && B == null) return 0;        if(A == null || A.length() == 0) return B.length();        if(B == null || B.length() == 0) return A.length();                int [][] dp = new int[A.length()+1][B.length()+1];                for(int i=0;i<A.length();i++){            for(int j=0;j<B.length();j++){                if(A.charAt(i) == B.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 dp[A.length()][B.length()];    }


0 0
原创粉丝点击