Java Array Common Prefix longestCommonContiguousSubstring(String s, String t)

Here you can find the source of longestCommonContiguousSubstring(String s, String t)

Description

Computes the longest common contiguous substring of s and t.

License

Open Source License

Declaration

public static int longestCommonContiguousSubstring(String s, String t) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from w  w  w  .ja va 2s. c  o m
     * Computes the longest common contiguous substring of s and t.
     * The LCCS is the longest run of characters that appear consecutively in
     * both s and t. For instance, the LCCS of "color" and "colour" is 4, because
     * of "colo".
     */
    public static int longestCommonContiguousSubstring(String s, String t) {
        if (s.isEmpty() || t.isEmpty()) {
            return 0;
        }
        int M = s.length();
        int N = t.length();
        int[][] d = new int[M + 1][N + 1];
        for (int j = 0; j <= N; j++) {
            d[0][j] = 0;
        }
        for (int i = 0; i <= M; i++) {
            d[i][0] = 0;
        }

        int max = 0;
        for (int i = 1; i <= M; i++) {
            for (int j = 1; j <= N; j++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1] + 1;
                } else {
                    d[i][j] = 0;
                }

                if (d[i][j] > max) {
                    max = d[i][j];
                }
            }
        }
        // System.err.println("LCCS(" + s + "," + t + ") = " + max);
        return max;
    }
}

Related

  1. longestCommonPath(String... paths)
  2. longestCommonPrefix(CharSequence str1, CharSequence str2)
  3. longestCommonPrefix(String a, String b)
  4. longestCommonPrefix(String one, String two)