如题,输出可能有多个最长字符串。
C# codes as below,
class Program
{
static void Main(string[] args)
{
string[] str = GetMaxString("1223344555666555777788887777");
foreach (string s in str)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
static string[] GetMaxString(string str)
{
if (str == string.Empty || str == null)
{
return null;
}
//Set the default value of the string number is 1
int stringNumber=1;
//Set the default value of the string length is 1
int stringLength = 1;
char[] allChars = new char[str.Length];
//Set the default value of the first element is str[0]
allChars[0] = str[0];
char currentChar=str[0];
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == currentChar)
{
count++;
if (count == stringLength)
{
//Set a bool mark to judge if the char has existed in the array allChars
bool ifExist = false;
//Go on a cycle to judge if the char has existed in the array allChars
for (int j = 0; j < stringNumber; j++)
{
if (allChars[j] == str[i])
{
ifExist = true;
}
}
//If this char hasn't been included in the array allChars, add it to the array.
if (!ifExist)
{
//Reset the number of the output strings
stringNumber++;
allChars[stringNumber - 1] = str[i];
}
}
else if (count > stringLength)
{
//Reset the number, length and value for the output strings
stringLength++;
stringNumber = 1;
allChars[0] = str[i];
}
}
else
{
//Reset current char's value
currentChar = str[i];
//Reset the value of count
count = 0;
//Recycle
i--;
}
}
//Name a string array
string[] result = new string[stringNumber];
//Set the value of the array
for (int i = 0; i < stringNumber; i++)
{
result[i] = new string(allChars[i], stringLength);
}
return result;
}
}
output:
7777
8888