Re: [問題] 同字母排列最長的字串
在不考慮超長字串且要自檔案讀出的情況的話,可以用正規運算式做:
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)
→
03/29 15:49, , 1F
03/29 15:49, 1F
※ 編輯: petrushka 來自: 140.125.251.180 (03/29 16:09)
討論串 (同標題文章)