看板 C_Sharp 關於我們 聯絡資訊
自原文推文中 lei 大的方法實作 int tIndex = 0, mIndex = 0, max = 1; if (input.Length > 1) { for (int i = 1; i < input.Length; i++) { if (input[i] != input[i - 1]) { int len = i - tIndex; if (len > max) { max = len; mIndex = tIndex; } tIndex = i; } } } else max = input.Length; return input.Substring(mIndex, max); 實測在字串長的情況下,效率會出現明顯差異 如果只有幾十到幾百字元的話,用哪種就無所謂了 ※ 引述《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: 120.126.146.20
F23ko:我絕得主要還是 t2 += temp; 的問題 03/26 16:23
adrianc:建議你實測看看... 03/28 21:13