最近在找工作,遇到這樣一道面試題:
對於給定的一個字符串,統計出該串中各個字符出現的次數,並打印出出現次數最多的那個字符
因為本人是個菜鳥,所以當時寫的思路是用遞歸
/*str 字符串, strA 第一個字符, strB數量最多的字符,MaxNum數量*/
static void GetLength(string str, string strA, string strB, int MaxNum)
{
if (str.Length <= 0)
{
Console.WriteLine(strB);
return;
}
strA = str.Substring(0, 1);
int Num = 0;
string strReplace = "";
strReplace = str.Replace(strA, "");
Num = str.Length - strReplace.Length;
if (Num > MaxNum)
{
strB = strA;
MaxNum = Num;
}
GetLength(strReplace, strA, strB, MaxNum);
}
但是后來,問了一些朋友,說遞歸算法其實效率會很低,用map就行了。於是,使用c#的Dictionary來實現了字符串統計
string str = "jintiantianqihaoqinglang";
Dictionary<char,int> dic=new Dictionary<char,int>();
foreach (char ch in str)
{
if (dic.Keys.Contains(ch))
{
dic[ch]++;
}
else
{
dic.Add(ch, 1);
}
}
再取dic中values值最大的key即為出現次數最多的字符
我寫的不是最好的方法,也希望各位大神多多提意見,嘻嘻,不過不喜勿噴!!!!