Java Array Common Prefix longestCommonPrefix3(String[] strs)

Here you can find the source of longestCommonPrefix3(String[] strs)

Description

Divide and conquer

License

Open Source License

Parameter

Parameter Description
strs a parameter

Declaration

public static String longestCommonPrefix3(String[] strs) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   www  . j  a  v a  2s .com*/
     * Divide and conquer
     *
     * @param strs
     * @return
     */
    public static String longestCommonPrefix3(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        return longestCommonPrefix(strs, 0, strs.length - 1);
    }

    private static String longestCommonPrefix(String[] strs, int l, int r) {
        if (l == r) {
            return strs[l];
        } else {
            int mid = (l + r) / 2;
            String lcpLeft = longestCommonPrefix(strs, l, mid);
            String rcpRight = longestCommonPrefix(strs, mid + 1, r);
            return commonPrefix(lcpLeft, rcpRight);
        }
    }

    private static String commonPrefix(String left, String right) {
        int min = Math.min(left.length(), right.length());
        for (int i = 0; i < min; i++) {
            if (left.charAt(i) != right.charAt(i)) {
                return left.substring(0, i);
            }
        }
        return left.substring(0, min);
    }
}

Related

  1. longestCommonPrefix(String[] strs)
  2. longestCommonPrefix(String[] strs)
  3. longestCommonPrefix(String[] strs, int l, int r)
  4. longestCommonPrefix1(String[] strs)
  5. longestCommonPrefix2(String[] strs)
  6. longestCommonPrefix4(String[] strs)
  7. longestCommonSequence(String str1, String str2)
  8. longestCommonSubstr(String s1, String s2)
  9. LongestCommonSubString(String firstString, String secondString)