package com.helloxin.leetcode.algorithms; /** * create by one leaf on 2017/12/12 */ public class Longest_common_prefix { /** * 根據String的indexOf和substring 來找他們的公衆部分 * @param strs * @return */ public static String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { //沒有子集會返回 -1,0是第一個位置 startWith while (strs[i].indexOf(prefix) != 0) { prefix = prefix.substring(0, prefix.length() - 1); //若是爲空 那麼沒有公衆前綴 if (prefix.isEmpty()) { return ""; } } } return prefix; } /** * 這個方法寫的就比較直觀了 取第一次字符,去遍歷其餘的字符串 看是否符合 * @param strs * @return */ public static String longestCommonPrefix2(String[] strs) { if (strs == null || strs.length == 0) { return ""; } //遍歷 第一個字符串 for (int i = 0; i < strs[0].length() ; i++){ char c = strs[0].charAt(i); //開始比對 for (int j = 1; j < strs.length; j ++) { //若是到了某個字符串的長度 或者已經不匹配 if (i == strs[j].length() || strs[j].charAt(i) != c) { return strs[0].substring(0, i); } } } return strs[0]; } /** * Divide and conquer 這是看solution 裏面 前輩們寫的第三種方法 想不到 並且我也不習慣使用遞歸的編程 * 或許是由於遞歸 沒有那麼直觀看到怎麼執行的 * 用於這個道題目到沒看出什麼優點 可是熟悉這個概念還不錯 * * @param strs * @return */ public static String longestCommonPrefix3(String[] strs) { if (strs == null || strs.length == 0) { return ""; } return longestCommonPrefix3(strs, 0 , strs.length - 1); } private static String longestCommonPrefix3(String[] strs, int l, int r) { if (l == r) { return strs[l]; } else { int mid = (l + r)/2; //遞歸調用 String lcpLeft = longestCommonPrefix3(strs, l , mid); String lcpRight = longestCommonPrefix3(strs, mid + 1,r); return commonPrefix(lcpLeft, lcpRight); } } 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); } /** * Binary search 在什麼狀況下 須要考慮這麼寫呢 這是solution中提供的第四種方法 * @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 str1 = strs[0].substring(0,len); for (int i = 1; i < strs.length; i++) { if (!strs[i].startsWith(str1)) { return false; } } return true; } public static void main(String[] args) { System.out.println(longestCommonPrefix3(new String[]{"YE","YE"})); } }
https://github.com/woshiyexinjie/leetcode-xingit