美文网首页
Longest Common Subsequence

Longest Common Subsequence

作者: BLUE_fdf9 | 来源:发表于2018-10-04 12:53 被阅读0次

题目

  1. Longest Common Subsequence
    Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

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

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

答案

public class Solution {
    /**
     * @param A: A string
     * @param B: A string
     * @return: The length of longest common subsequence of A and B
     */
    public int longestCommonSubsequence(String A, String B) {
        // write your code here
        int m = A.length(), n = B.length();
        int[][] f = new int[m + 1][n + 1];
        
        for(int i = 0; i <= n; i++) {
            for(int j = 0; j <= m; j++) {
                // LCS of any string with empty string is 0
                if(i == 0 || j == 0) {
                    f[i][j] = 0;
                    continue;
                }
                
                if(A.charAt(i - 1) == B.charAt(j - 1))
                    f[i][j] = Math.max(f[i][j], f[i - 1][j - 1] + 1);
                else
                    f[i][j] = Math.max(f[i][j - 1], f[i - 1][j]);
            }
        }
        return f[m][n];
    }
}

上面的答案f[i][j]是定义为LCS(A[0...i-1], B[0...j-1])
下面的答案f[i][j]是定义为LCS(A[0...i], B[0...j])

public class Solution {
    /**
     * @param A: A string
     * @param B: A string
     * @return: The length of longest common subsequence of A and B
     */
    public int longestCommonSubsequence(String A, String B) {
        // write your code here
        int m = A.length(), n = B.length();
        if(m == 0 || n == 0) return 0;
        int[][] f = new int[m][n];
        
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(i == 0 || j == 0) {
                    if(A.charAt(i) == B.charAt(j)) f[i][j] = 1;
                    else f[i][j] = 0;
                    continue;
                }
                
                if(A.charAt(i) == B.charAt(j))
                    f[i][j] = 1 + f[i - 1][j - 1];
                else
                    f[i][j] = Math.max(f[i][j - 1], f[i - 1][j]);
            }
        }
        return f[m - 1][n - 1];
    }
}

相关文章

网友评论

      本文标题:Longest Common Subsequence

      本文链接:https://www.haomeiwen.com/subject/shjxaftx.html