In two strings:
\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"
should return
\"Mary Had a \"
A very easy solution can be:
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
String result = strs[0];
for (int i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(result)) {
result = result.substring(0, result.length() - 1);
}
}
return result;
}
You don't need to use a StringBuilder
- just return the substring:
public String greatestCommonPrefix(String a, String b) {
int minLength = Math.min(a.length(), b.length());
for (int i = 0; i < minLength; i++) {
if (a.charAt(i) != b.charAt(i)) {
return a.substring(0, i);
}
}
return a.substring(0, minLength);
}
This solution applied to a multiple string array. When you have 3 or 4 strings, it's better to use StringBuilder. For 2 strings, it's ok to use substring. Code in C#:
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0) return string.Empty;
Array.Sort(strs);
var first = strs[0];
var last = strs[strs.Length - 1];
var sb = new StringBuilder();
for(int i = 0; i< first.Length; i++)
{
if(first[i] != last[i])
{
break;
}
sb.Append(first[i]);
}
return sb.ToString();
}