作者petrushka (不放过自己)
看板C_Sharp
标题Re: [问题] 同字母排列最长的字串
时间Mon Mar 29 15:43:09 2010
在不考虑超长字串且要自档案读出的情况的话,可以用正规运算式做:
int maxLength = 0;
string maxString = string.Empty;
string pattern = @"(\w)\1+";
Match match = Regex.Match( input, pattern );
while( match.Success )
{
if( match.Value.Length > maxLength )
{
maxLength = match.Value.Length;
maxString = match.Value;
}
match = match.NextMatch();
}
最後的 maxLength 即找到的最长字串长度,maxString即该字串。
如果你想要找连续字母在5个以上的,可以修改pattern为以下样式:
string pattern = @"(\w)\1{5,}";
那个数字5就是最小长度,依需要修改。
※ 引述《paulyanzi (消失)》之铭言:
: 想到一个问题 ,
: 如果是给一个字串,从中找出连续同字母排列最长的字串并输出,
: EX: input ="djaaakkppppewqqqTwyyyyy";
: 结果应该是:yyyyy
: input ="djaaakkppppewqqqTwyyy";
: 结果应该是:pppp
: 我简单的方法如下
: string input ="ddddjaaakkpppewqqqTwyyyyy";
: string t2="",max="";
: foreach (char temp in input)
: {
: if (t2.EndsWith(temp.ToString()))
: {
: t2 += temp;
: }
: else
: { //当换字母的时候才会做
: if(t2.Length>max.Length)
: max = t2;
: t2 = temp.ToString();
: }
: }
: if(t2.Length>max.Length)max=t2;
: Console.WriteLine(max);
: 但是感觉应该会有更好的做法 不知道有没有人有其他想法呢?
--
对於已经无法拥有的
唯一能做的是
不要忘记
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.125.251.180
※ 编辑: petrushka 来自: 140.125.251.180 (03/29 15:45)
1F:→ petrushka:如果结果为0或空字串,表示没有连续字母~ 03/29 15:49
※ 编辑: petrushka 来自: 140.125.251.180 (03/29 16:09)