Java Array Common Prefix longestCommonPrefix4(String[] strs)

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

Description

Binary search

License

Open Source License

Parameter

Parameter Description
strs a parameter

Declaration

public static String longestCommonPrefix4(String[] strs) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*  www .j ava  2 s  .  c  o m*/
     * Binary search
     *
     * @param strs
     * @return
     */
    public static String longestCommonPrefix4(String[] strs) {
        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;
        int high = minLen;
        while (low <= high) {
            int middle = (low + high) / 2;
            if (isCommonPrefix(strs, middle)) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }

        }
        return strs[0].substring(0, (low + high) / 2);
    }

    private static boolean isCommonPrefix(String[] strs, int len) {
        String str = strs[0].substring(0, len);
        for (int i = 1; i < strs.length; i++) {
            if (!strs[i].startsWith(str)) {
                return false;
            }
        }
        return true;
    }
}

Related

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