查找列表中最短的条目。
所以我们使用“今天”。
在“Today”中构建一个连续字符的字符串列表,将字符串的长度向下到每个字符,以“最长的优先”顺序。
“今天”,
“户田”、“今天”、
“Tod”、“oda”、“day”、
“到”、“od”、“da”、“ay”、
“今天”
枚举这个列表,找到所有其他字符串都包含该条目的第一个条目。
List<string> words = new List<string> { "Today", "Monday", "Tuesday", "Wednesday" };
// Select shortest word in the list
string shortestWord = (from word in words
orderby word.Length
select word).First();
int shortWordLength = shortestWord.Length;
// Build up the list of consecutive character strings, in length order.
List<string> parts = new List<string>();
for (int partLength = shortWordLength; partLength > 0; partLength--)
{
for (int partStartIndex = 0; partStartIndex <= shortWordLength - partLength; partStartIndex++)
{
parts.Add(shortestWord.Substring(partStartIndex, partLength));
}
}
// Find the first part which is in all the words.
string longestSubString = (from part in parts where words.All(s => s.Contains(part)) select part).FirstOrDefault();
// longestSubString is the longest part of all the words, or null if no matches are found.
编辑
多想一点,就可以优化一点。
您无需建立零件列表 - 只需在生成每个零件时对其进行测试。此外,通过按长度顺序对单词列表进行排序,您总是首先测试最短的字符串以更快地拒绝候选部分。
string longestSubString = null;
List<string> words = new List<string> { "Todays", "Monday", "Tuesday" };
// Sort word list by length
List<string> wordsInLengthOrder = (from word in words
orderby word.Length
select word).ToList();
string shortestWord = wordsInLengthOrder[0];
int shortWordLength = shortestWord.Length;
// Work through the consecutive character strings, in length order.
for (int partLength = shortWordLength; (partLength > 0) && (longestSubString == null); partLength--)
{
for (int partStartIndex = 0; partStartIndex <= shortWordLength - partLength; partStartIndex++)
{
string part = shortestWord.Substring(partStartIndex, partLength);
// Test if all the words in the sorted list contain the part.
if (wordsInLengthOrder.All(s => s.Contains(part)))
{
longestSubString = part;
break;
}
}
}
Console.WriteLine(longestSubString);