我的解答
public String longestCommonPrefix(String[] strs) { String longestCommonPrefix = ""; for (int j = 0; j < strs.length; j++) { if (j == 0) { longestCommonPrefix = strs[j]; continue; } if (longestCommonPrefix.length() > strs[j].length()) { longestCommonPrefix = strs[j]; } } if (longestCommonPrefix.length() == 0) return ""; longestCommonPrefix = strs[0].substring(0, longestCommonPrefix.length()); for (String string : strs) { String perfix = string; if (longestCommonPrefix.length() <= string.length()){ perfix = string.substring(0, longestCommonPrefix.length()); } if (longestCommonPrefix.equals(perfix)) { continue; } else { while (!longestCommonPrefix.equals(perfix)) { int length = longestCommonPrefix.length(); if (longestCommonPrefix.length() == 1) { perfix = perfix.substring(0, 1); longestCommonPrefix = longestCommonPrefix.substring(0, 1); if (!perfix.equals(longestCommonPrefix)) { longestCommonPrefix = ""; } break; } else { perfix = perfix.substring(0, length - 1); longestCommonPrefix = longestCommonPrefix.substring(0, length - 1); } } } } return longestCommonPrefix; }