Java Array Common Prefix LongestCommonSubString(String firstString, String secondString)

Here you can find the source of LongestCommonSubString(String firstString, String secondString)

Description

Longest Common Sub String

License

Open Source License

Declaration

public static String LongestCommonSubString(String firstString, String secondString) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String LongestCommonSubString(String firstString, String secondString) {
        //        I search for help in Wikipedia for this algorithm
        StringBuilder sb = new StringBuilder();
        if (null == firstString || null == secondString) {
            return "";
        }//w w  w.java 2 s  . c o m
        int[][] num = new int[firstString.length()][secondString.length()];
        int maxlen = 0;
        int lastSubsBegin = 0;

        for (int i = 0; i < firstString.length(); i++) {
            for (int j = 0; j < secondString.length(); j++) {
                if (firstString.charAt(i) == secondString.charAt(j)) {
                    if ((i == 0) || (j == 0)) {
                        num[i][j] = 1;
                    } else {
                        num[i][j] = 1 + num[i - 1][j - 1];
                    }

                    if (num[i][j] > maxlen) {
                        maxlen = num[i][j];
                        int thisSubsBegin = i - num[i][j] + 1;
                        if (lastSubsBegin == thisSubsBegin) {
                            sb.append(firstString.charAt(i));
                        } else {
                            lastSubsBegin = thisSubsBegin;
                            sb = new StringBuilder();
                            sb.append(firstString.substring(lastSubsBegin, i + 1));
                        }
                    }
                }
            }
        }
        return sb.toString();
    }
}

Related

  1. longestCommonPrefix2(String[] strs)
  2. longestCommonPrefix3(String[] strs)
  3. longestCommonPrefix4(String[] strs)
  4. longestCommonSequence(String str1, String str2)
  5. longestCommonSubstr(String s1, String s2)
  6. longestCommonSubstring(String S1, String S2)
  7. longestCommonSuffix(final byte[] seq1, final byte[] seq2, final int maxLength)