如何计算以下最后5种颜色的两种颜色的最长序列(使用C#)?
var colorValues = new []{"Blue", "Yellow","Black","Yellow",
"Green","Yellow", "Yellow","Red"}
在上述预期序列中是“黄色”,“绿色”,“黄色”,“黄色”。
答案 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()));
它给出了:
黄色,绿色,黄色,黄色