В LINQ:
// The strings (it's equivalent to new string[])
var strs = new[] { "acks", "top", "cat", "gr", "by", "bar", "lap", "st", "ely", "ades" };
// We group the strings by length.
var strsByLength = strs.ToLookup(p => p.Length);
// For each string we match the string with all the strings with the "right" length (6 - current string length) and we sum them (p, q) => p + q.
var result = strs.SelectMany(p => strsByLength[6 - p.Length], (p, q) => p + q);
Я использую ToLookup
, чтобы сделать эту проблему "средней" сложности чуть меньше, чем O (n ^ 2). Ясно, что если все строки длинные 3, проблема по-прежнему O (n ^ 2).
Я использую SelectMany
, который является немного продвинутым LINQ.
Я добавлю, если у вас есть словарь "хороших" слов, решение может быть таким. Он использует словарь как черный ящик: вы можете проверить, находится ли слово в словаре (технически HashSet
), но вы не можете напрямую использовать словарь, чтобы помочь вам найти слова.
// The list of good words
var words = new[] { "stacks", "laptop", "grades", "barely" };
// Made in an `HashSet` to make it O(1) to check for them.
var wordsSet = new HashSet<string>(words);
// Here we create a temporary object (p, q) => new { p, q, sum = p + q } containing the two "parts" of the word and the complete word and then we filter the result for only the words contained in the wordsSet.
var result2 = strs.SelectMany(p => strsByLength[6 - p.Length], (p, q) => new { p, q, sum = p + q }).Where(p => wordsSet.Contains(p.sum));