纵向扫描
package com.alg.Three;/** 最长公共前缀 * 纵向挨个比对字符是否相同 * @author fuyao * @date 2022年06月20日 5:08 下午 */public class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0){ return ""; } int length = strs[0].length(); int count = strs.length; for (int i = 0; i < length; i++) { for (int j = 1; j < count; j++) { if (strs[j].length() == i || strs[j].charAt(i) != strs[0].charAt(i)){ return strs[0].substring(i); } } } return strs[0]; }}
分治法
public String longestCommonPrefix1(String[] strs) { if (strs == null || strs.length == 0) { return ""; } else { return longestCommonPrefix(strs, 0, strs.length - 1); } } private String longestCommonPrefix(String[] strs, int start, int end) { if (start == end) { return strs[start]; } else { int mid = (end - start) / 2 + start; String lcpLeft = longestCommonPrefix(strs, start, mid); String lcpRight = longestCommonPrefix(strs, mid + 1, end); return commonPrefix(lcpLeft, lcpRight); } } private String commonPrefix(String lcpLeft, String lcpRight) { int minlength = Math.min(lcpLeft.length(), lcpRight.length()); for (int i = 0; i < minlength; i++) { if (lcpLeft.charAt(i) != lcpRight.charAt(i)) { return lcpLeft.substring(0, i); } } return lcpLeft.substring(0, minlength); }
二分法
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } int minLength = Integer.MAX_VALUE; for (String str : strs) { minLength = Math.min(minLength, str.length()); } int low = 0, high = minLength; while (low < high) { int mid = (high - low + 1) / 2 + low; if (isCommonPrefix(strs, mid)) { low = mid; } else { high = mid - 1; } } return strs[0].substring(0, low); } public boolean isCommonPrefix(String[] strs, int length) { String str0 = strs[0].substring(0, length); int count = strs.length; for (int i = 1; i < count; i++) { String str = strs[i]; for (int j = 0; j < length; j++) { if (str0.charAt(j) != str.charAt(j)) { return false; } } } return true; }}