Calculate the max count of continuous characters
//GNU General Public License version 2 (GPLv2)
//http://cbasetest.codeplex.com/license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SDFL.Helper
{
public class StrHelper
{
/// <summary>
/// a function to calculate the max count of continuous characters.
/// For example, input abb and it will return 2, input abbbcc and it will return 3, etc..
/// </summary>
/// <hirtory>
/// [Dylan] 08/17/2009 Fix bug, if max list exist in the end, can't got it. e.g. "affddccccc"
/// [Dylan] 08/17/2009 Fix bug, if only one continuous list, and in the end, DupList is null, e.g. "aff"
/// [Dylan] 08/17/2009 Fix bug, if only one char. e.g "a"
/// </hirtory>
/// <param name="str"></param>
/// <returns>max count of continuous characters</returns>
public static Int32 MaxofDupCharacter(string str)
{
int length = str.Length;
bool isDup = false;
int iPre = 0;
int iLatter = 1;
List<int> DupList = new List<int>();
// [Dylan] 08/17/2009 Fix bug, if only one char. e.g "a"
if (str.Length == 1)
return 1;
for (int i = 0; i < length -1; i++)
{
if (str[iLatter] == str[iPre])
{
isDup = true;
// [Dylan] 08/17/2009 Fix bug, if only one continuous list, and in the end, DupList is null, e.g. "aff"
if (iLatter == length -1 && DupList.Count == 0)
{
DupList.Add(iLatter - iPre + 1);
}
// [Dylan] 08/17/2009 Fix bug, if max list exist in the end, can't got it. e.g. "affddccccc"
// if true, it indicate that end region is still a continuous list.
if (iPre< iLatter -1)
{
DupList.Add(iLatter - iPre+1);
}
}
else
{
if (isDup)
{
DupList.Add(iLatter - iPre);
}
isDup = false;
iPre = iLatter;
}
iLatter++;
}
return int.Parse(DupList.Max().ToString());
}
}
}
Related examples in the same category