On the pro side, it is much faster because accessing an array is constant in time, there is literally no search or indexing, on the con side it uses a static array of 255 int
. Also in C#, if you follow the guidelines of Resharper or StyleCop, they will recommend you to use var when you can and to not use '_' prefixing:
public static int GetMaximumOccurence(string str)
{
var countPerChar = new Dictionary<char, int>();
int maxcount = 0;
foreach (char c in str)
{
int newVal;
if (!countPerChar.ContainsKeyTryGet(c, newVal))
newVal = (countPerChar[c] = 1);
else
newVal = (countPerChar[c] += 1);
maxcount = Math.Max(maxcount, newVal);
}
return maxcount;
}
dss539 suggestion leads to:
public static int GetMaximumOccurence(string str)
{
var countPerChar = new Dictionary<char, int>();
int maxcount = 0;
foreach (char c in str)
{
int newVal;
countPerChar.TryGetValue(c, out newVal); // NewVal is set to 0 if the value is not found
maxcount = Math.Max(maxcount, (countPerChar[c] = newVal + 1));
}
return maxcount;
}