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

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


在上面的预期顺序中是“黄色”,“绿色”,“黄色”,“黄色”。

最佳答案

尝试这个:

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()));


它给:


  黄,绿,黄,黄

关于c# - 如何在C#中找到最长的颜色序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41691685/

10-09 02:27