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

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...