如何在C#中找到最长的颜色序列

时间:2017-01-17 07:54:21

标签: c# linq logic sequence

如何计算以下最后5种颜色的两种颜色的最长序列(使用C#)?

var colorValues = new []{"Blue", "Yellow","Black","Yellow",
                         "Green","Yellow", "Yellow","Red"}

在上述预期序列中是“黄色”,“绿色”,“黄色”,“黄色”。

1 个答案:

答案 0 :(得分:2)

试试这个:

var colorValues = new[]
{
    "Blue", "Yellow", "Black", "Yellow",
    "Green", "Yellow", "Yellow", "Red"
};

var query =
    from n in Enumerable.Range(0, colorValues.Length)
    from l in Enumerable.Range(1, colorValues.Length - n)
    let subseq = colorValues.Skip(n).Take(l).ToArray()
    where subseq.Distinct().Count() == 2
    orderby subseq.Count() descending
    select subseq;

Console.WriteLine(String.Join(", ", query.First()));

它给出了:

  

黄色,绿色,黄色,黄色