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