Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

Although a regex or custom Linq extension is fine, if you don't mind "doing it the old way" you can achieve your result with two temporary variables and a classic foreach loop.

The logic is pretty simple, and runs in O(n). Loop through your string and compare the current character with the previous one.

If it's the same, increase your count. If it's different, reset it to 1.

Then, if your count is greater than the previous recorded max count, overwrite the rchar with your current character.

string text = "hello dear";

char rchar = text[0];
int rcount = 1;

int currentCount = 0;
char previousChar = char.MinValue;
foreach (char character in text)
{
    if (character != previousChar)
    {
        currentCount = 1;
    }
    else
    {
        currentCount++;
    }

    if (currentCount >= rcount)
    {
        rchar = character;
        rcount = currentCount;
    }

    previousChar = character;
}

string routput = new string(rchar, rcount);

It's indeed verbose, but gets the job done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...