In two strings:
\"Mary Had a Little Lamb\"
\"Mary Had a Big Lamb\"
should return
\"Mary Had a \"
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();
}