您的位置:首页 > 其它

写一个函数(maxLength)返回该参数中连续相同字母的最大个数及该字母

2010-07-14 17:14 267 查看
1. 一个字符串参数(value)由字母(a-z,A-Z)组成,且最大字符位数为40,要求写一个函数(maxLength)返回该参数中连续相同字母的最大个数及该字母,如果最大位数有多个,则返回第一个。例:字符串“aaaddxxxxddddxxxx”,返回值为:“x,4”。
要求:请考虑代码执行的效率并注意编码的风格。

class Program
{
static void Main(string[] args)
{
string s = "aaaddxxxxxbbbbbbbbddddxxxx";
Console.WriteLine(GetMaxLength(s));
}
public static string GetMaxLength(string str)
{
char maxChar = new char();
int maxCount = 0;
char tempChar = new char();
int tempCount = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == tempChar)
tempCount ++;
else
{
if (tempCount > maxCount)
{
maxChar = tempChar;
maxCount = tempCount;
}
tempChar = str[i];
tempCount = 1;
}
}
return maxChar.ToString() + "," + maxCount.ToString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐