Byyo Byyo - 1 month ago 9
C# Question

Find the longest repetition character in String

Let's say i have a string like

string text = "hello dear";


Then I want to determine the longest repetition of coherented characters - in this case it would be
ll
. If there are more than one with the same count, take any.

I have tried to solve this with linq

char rchar = text.GroupBy(y => y).OrderByDescending(y => y.Count()).Select(x => x).First().Key;
int rcount = text.Where(x => x == rchar).Count();
string routput = new string(rchar, rcount);


But this returns
ee
. Am I on the right track?

w.b w.b
Answer Source

Another solution using LINQ:

string text = "hello dear";
string longestRun = new string(text.Select((c, index) => text.Substring(index).TakeWhile(e => e == c))
                                   .OrderByDescending(e => e.Count())
                                   .First().ToArray());

Console.WriteLine(longestRun); // ll

It selects a sequence of substrings starting with the same repeating character, and creates the result string with the longest of them.