在字符串中找到最长的重复字符

编程入门 行业动态 更新时间:2024-10-26 14:36:23
本文介绍了在字符串中找到最长的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个像这样的字符串

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.

更多推荐

在字符串中找到最长的重复字符

本文发布于:2023-11-30 01:06:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648206.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   最长   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!