2016年6月17日星期五

[LintCode] #79 Longest Common Substring

Problem: http://www.lintcode.com/en/problem/longest-common-substring/
Solution1: Dynamic Programming, use 2-dimension array
public class Solution {
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    public int longestCommonSubstring(String A, String B) {
        // int d[i][j] : the length of the common substring nearest to the end of A.substring(i) and B.substring(j)
        // d[i][j] = d[i - 1][j - 1] + 1, A[i] == B[j]
        //         = 0, A[i] != B[j]
        
        int max = 0;
        if (A == null || B == null) {
            return max;
        }
        
        int d[][] = 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 (i == 0 || j == 0) {
                    d[i][j] = 0; //init
                    continue;
                }
                if (A.charAt(i - 1) == B.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1] + 1;
                } else {
                    d[i][j] = 0;
                }
                max = max > d[i][j] ? max : d[i][j];
            }
        }
        return max;
    }
}

Solution2(super demon version DP): http://www.jiuzhang.com/solutions/longest-common-substring/
Homework: Listen to NineChapter DP lecture :p

没有评论:

发表评论