Java Array Common Prefix longestCommonSubstr(String s1, String s2)

Here you can find the source of longestCommonSubstr(String s1, String s2)

Description

This implementation appears O(n^2) .

License

Open Source License

Parameter

Parameter Description
s1 a parameter
s2 a parameter

Return

the length of the longest common substring

Declaration

public static int longestCommonSubstr(String s1, String s2) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   ww  w . ja  v a 2  s . com*/
     * This implementation appears {@code O(n^2)}. This is slower than a suffix
     * trie implementation, which is {@code O(n+m)}. The code below is copied
     * from wikipedia.
     *
     * @param s1
     * @param s2
     * @return the length of the longest common substring
     */
    public static int longestCommonSubstr(String s1, String s2) {
        if (s1.isEmpty() || s2.isEmpty()) {
            return 0;
        }

        int m = s1.length();
        int n = s2.length();
        int cost = 0;
        int maxLen = 0;
        int[] p = new int[n];
        int[] d = new int[n];

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (s1.charAt(i) != s2.charAt(j)) {
                    cost = 0;
                } else {
                    if ((i == 0) || (j == 0)) {
                        cost = 1;
                    } else {
                        cost = p[j - 1] + 1;
                    }
                }
                d[j] = cost;

                if (cost > maxLen) {
                    maxLen = cost;
                }
            } // for {}

            int[] swap = p;
            p = d;
            d = swap;
        }

        return maxLen;
    }
}

Related

  1. longestCommonPrefix1(String[] strs)
  2. longestCommonPrefix2(String[] strs)
  3. longestCommonPrefix3(String[] strs)
  4. longestCommonPrefix4(String[] strs)
  5. longestCommonSequence(String str1, String str2)
  6. LongestCommonSubString(String firstString, String secondString)
  7. longestCommonSubstring(String S1, String S2)
  8. longestCommonSuffix(final byte[] seq1, final byte[] seq2, final int maxLength)