C#:如何从 LINQ 表达式的字符串列表中获取最长的公共前缀
C#:How to get the longest common prefix from a list of strings LINQ expression
我正在努力学习 LINQ
我想了解如何从字符串列表中获取最长的公共前缀
{“a”,“abC”,“abcD”}
会 return “ab”。常见于至少 1 个其他字符串中。尽管“a”对于所有 3 个都是通用的,但我想得到“ab”,因为 2 个元素共享此前缀并且“ab”比“a”长
这是一个有趣的挑战,这是我的解决方案:
var array = new []{"a","abC","abcD"};
var longestCommonPrefix = Enumerable.Range(1, array.Max(_ => _)!.Length)
.Select(i =>
{
var grouped = array.Where(x => x.Length >= i)
.GroupBy(x => x[..i])
.Where(x => x.Count() > 1)
.OrderByDescending(x => x.Count())
.Select(x => new { LongestCommonPrefix = x.Key })
.FirstOrDefault();
return grouped?.LongestCommonPrefix ?? string.Empty;
}).Max();
var longestCommonPrefix = (words.FirstOrDefault() ?? String.Empty)
.Substring(0,
Enumerable.Range(0, words.Any() ? words.Min(x => x.Length) + 1 : 0)
.Where(x => words.Select(w => w.Substring(0, x))
.Distinct().Count() == 1).DefaultIfEmpty(0).Max()
);
我正在努力学习 LINQ 我想了解如何从字符串列表中获取最长的公共前缀 {“a”,“abC”,“abcD”} 会 return “ab”。常见于至少 1 个其他字符串中。尽管“a”对于所有 3 个都是通用的,但我想得到“ab”,因为 2 个元素共享此前缀并且“ab”比“a”长
这是一个有趣的挑战,这是我的解决方案:
var array = new []{"a","abC","abcD"};
var longestCommonPrefix = Enumerable.Range(1, array.Max(_ => _)!.Length)
.Select(i =>
{
var grouped = array.Where(x => x.Length >= i)
.GroupBy(x => x[..i])
.Where(x => x.Count() > 1)
.OrderByDescending(x => x.Count())
.Select(x => new { LongestCommonPrefix = x.Key })
.FirstOrDefault();
return grouped?.LongestCommonPrefix ?? string.Empty;
}).Max();
var longestCommonPrefix = (words.FirstOrDefault() ?? String.Empty)
.Substring(0,
Enumerable.Range(0, words.Any() ? words.Min(x => x.Length) + 1 : 0)
.Where(x => words.Select(w => w.Substring(0, x))
.Distinct().Count() == 1).DefaultIfEmpty(0).Max()
);