Leetcode: 編寫一個函數來查找字符串數組中的最長公共前綴。若是不存在公共前綴,返回空字符串 ""。數組
思路:先將字符串數組排序,在比較第一個字符串與最後一個字符串的公共前綴便可
eg:["abcddd","abbddd","abccc"] -> ["abbddd","abccc","abcddd"],
只需比較第一個字符串"abbddd"與最後一個字符串"abcddd"app
代碼實現函數
/** * 最長公共前綴 LCP(longest common prefix) * Leetcode: 編寫一個函數來查找字符串數組中的最長公共前綴。若是不存在公共前綴,返回空字符串 ""。 * * 思路:先將字符串數組排序,在比較第一個字符串與最後一個字符串的公共前綴便可 * eg:["abcddd","abbddd","abccc"] -> ["abbddd","abccc","abcddd"], * 只需比較第一個字符串"abbddd"與最後一個字符串"abcddd" */ public class LCP { public String solution(String[] strs){ //保存公共前綴 StringBuffer lcpStr = new StringBuffer(); if(strs == null){ return lcpStr.toString(); } //排序 Arrays.sort(strs); String first = strs[0]; String last = strs[strs.length - 1]; int firstLength = first.length(); int lastLength = last.length(); int count = firstLength > lastLength ? lastLength : firstLength; for(int i = 0;i < count;i++){ if(first.charAt(i) == last.charAt(i)){ lcpStr.append(first.charAt(i)); }else{ //不同則退出循環 break; } } return lcpStr.toString(); } public static void main(String[] args) { LCP lcp = new LCP(); String[] strs = {"abcddd","abbddd","abccc"}; System.out.println(lcp.solution(strs)); } }