public class LongestCommonSubstring {

    public static void main(String[] args) {
        String text1 = "abcde";
        String text2 = "ce";

        System.out.println(longestConsecutiveCommonSubsequence(text1, text2));

        text1 = "ezupkr";
        text2 = "ubmrapg";

        System.out.println(longestConsecutiveCommonSubsequence(text1, text2));

        text1 = "abcde";
        text2 = "bcd";

        System.out.println(longestConsecutiveCommonSubsequence(text1, text2));
    }

    public static int longestConsecutiveCommonSubsequence(String text1, String text2) {
        int ans = 0;

        if (text1 == null || text1.length() == 0 || text2 == null || text2.length() == 0) {
            return ans;
        }

        int len1 = text1.length();
        int len2 = text2.length();

        // row represents the length of text2, col represents the length of text1
        // initially, values for every cell is 0 by default.
        int[][] dp = new int[len2 + 1][len1 + 1];

        for (int i = 1; i <= len2; i++) {
            for (int j = 1; j <= len1; j++) {
                if (text1.charAt(j - 1) == text2.charAt(i - 1)) {
                    // text1 and text2 both move forward one step
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = 0;
                }

                ans = Math.max(ans, dp[i][j]);
            }
        }

        return ans;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-04 08:34:13

results matching ""

    No results matching ""