public class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { if(strs == null) return null; if(strs.length == 0) return ""; String s = strs[0]; for(int i = 0; i < s.length(); i ++) { for(int j = 1; j < strs.length; j ++) { if(strs[j].length()==i||strs[j].charAt(i)!= s.charAt(i))//条件先后顺序不能写反了,否则数组越界 return s.substring(0,i); } } return s; } public static void main(String[] args) { LongestCommonPrefix lc = new LongestCommonPrefix(); String[] strs = {"aa" , "a"}; System.out.println(lc.longestCommonPrefix(strs)); } }