例如:class、classify、clean的公共最长前缀为cl。
例如:count、key、open的最长公共前缀为空字符串。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>() { "class", "classify", "clean" };
Console.WriteLine(GetCommonText(list));
Console.ReadKey(true);
}
static string GetCommonText(List<string> list)
{
string text = string.Empty;
if (list == null || list.Count < 2)
{
return text;
}
// 最短字符串
int length = list[0].Length;
int index = 0;
for (int i = 1; i < list.Count; i++)
{
if (list[i].Length <= length)
{
length = list[i].Length;
index = i;
}
}
// 求公共前缀
char[] charArray = list[index].ToArray();
bool isEqual = true;
for (int i = 0; i < charArray.Length; i++)
{
for (int j = 0; j < list.Count; j++)
{
char[] tempArray = list[j].ToArray();
if (tempArray[i] != charArray[i])
{
isEqual = false;
break;
}
}
if (isEqual)
{
text += charArray[i].ToString();
}
else
{
break;
}
}
return text;
}
}
}