Here you can find the source of longestCommonPrefix4(String[] strs)
Parameter | Description |
---|---|
strs | a parameter |
public static String longestCommonPrefix4(String[] strs)
//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; } }