先对字符串排序,第一个和最后一个差别最大,计算差别最大的最小公共子串变为全局的最小公共子串
package com.bupt; import java.util.Arrays; public class T14 { public String longestCommonPrefix(String[] strs) { Arrays.sort(strs); String a = strs[0]; String b = strs[strs.length-1]; int min = Math.min(a.length(),b.length()); int commonLength = 0 ; for (int i = 0; i < min; i++) { if(a.substring(0,i+1).equals(b.substring(0,i+1))){ commonLength++; }else{ break; } } if(commonLength==0) return ""; return a.substring(0,commonLength); } public static void main(String[] args) { String []strs = {"1flower","2flow","3flight"}; System.out.println(new T14().longestCommonPrefix(strs)); } }