本文介绍了在字符串中找到最长的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个像这样的字符串
Let's say i have a string like
string text = "hello dear";
然后,我想确定连贯字符的最长重复-在这种情况下,它将是 ll
.如果有多个相同的计数,则取一个.
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.
我试图用linq解决这个问题
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);
但这将返回 ee
.我在正确的轨道上吗?
But this returns ee
. Am I on the right track?
推荐答案
使用LINQ的另一种解决方案:
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.
这篇关于在字符串中找到最长的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!