Java Utililty Methods Array Common Prefix

List of utility methods to do Array Common Prefix

Description

The list of methods to do Array Common Prefix are organized into topic(s).

Method

StringlongestCommonPrefix4(String[] strs)
Binary search
if (strs == null || strs.length == 0) {
    return "";
int minLen = Integer.MAX_VALUE;
for (String str : strs) {
    minLen = Math.min(minLen, str.length());
int low = 1;
...
intlongestCommonSequence(String str1, String str2)
longest Common Sequence
if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0) {
    return 0;
char[] cs1 = str1.toCharArray(), cs2 = str2.toCharArray();
int[][] longest = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
    longest[i][0] = 0;
for (int i = 0; i <= str2.length(); i++) {
    longest[0][i] = 0;
for (int i = 1; i <= str1.length(); i++) {
    for (int j = 1; j <= str2.length(); j++) {
        int max = Integer.max(longest[i - 1][j], longest[i][j - 1]);
        if (cs1[i - 1] == cs2[j - 1]) {
            max = Integer.max(longest[i - 1][j - 1] + 1, max);
        longest[i][j] = max;
return longest[str1.length()][str2.length()];
intlongestCommonSubstr(String s1, String s2)
This implementation appears O(n^2) .
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];
...
StringLongestCommonSubString(String firstString, String secondString)
Longest Common Sub String
StringBuilder sb = new StringBuilder();
if (null == firstString || null == secondString) {
    return "";
int[][] num = new int[firstString.length()][secondString.length()];
int maxlen = 0;
int lastSubsBegin = 0;
for (int i = 0; i < firstString.length(); i++) {
...
StringlongestCommonSubstring(String S1, String S2)
longest Common Substring
int Start = 0;
int Max = 0;
for (int i = 0; i < S1.length(); i++) {
    for (int j = 0; j < S2.length(); j++) {
        int x = 0;
        while (S1.charAt(i + x) == S2.charAt(j + x)) {
            x++;
            if (((i + x) >= S1.length()) || ((j + x) >= S2.length()))
...
intlongestCommonSuffix(final byte[] seq1, final byte[] seq2, final int maxLength)
Get the length of the longest common suffix of seq1 and seq2
if (seq1 == null)
    throw new IllegalArgumentException("seq1 is null");
if (seq2 == null)
    throw new IllegalArgumentException("seq2 is null");
if (maxLength < 0)
    throw new IllegalArgumentException("maxLength < 0 " + maxLength);
final int end = Math.min(seq1.length, Math.min(seq2.length, maxLength));
for (int i = 0; i < end; i++) {
...