public String longestCommonPrefix(String[] strs) {
if (strs.length == 0) return "";
String common = strs[0];
for (int i = 1; i < strs.length; i++) {
common = sharedPrefix(common, strs[i]);
if (common.length() == 0) break;
}
return common;
}
// Helper for longestCommonPrefix
public String sharedPrefix(String currentPrefix, String string) {
if (currentPrefix == null || string == null) return "";
// If we contain the current prefix then go with it.
// Otherwise we need to work backwards and figure it out.
if (string.startsWith(currentPrefix)) {
return currentPrefix;
}
String matchingSubrange = "";
for (int i = 0; i < currentPrefix.length() && i < string.length(); i++) {
String subrange = currentPrefix.substring(0, i + 1);
if (string.startsWith(subrange)) {
matchingSubrange = subrange;
} else {
return matchingSubrange;
}
}
return matchingSubrange;
}