void Test()
{
string a = "abccabccabccabccabccabccabccabccabccabccabccabccabccabccabccabcc";
string b = "bcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcacbcac";
IsAnagramSimple(a, b);
IsAnagramFast(a, b);
}
private bool IsAnagramSimple(string a, string b)
{
return a.OrderBy(c => c).SequenceEqual(b.OrderBy(c => c));
}
private bool IsAnagramFast(string a, string b)
{
if (a.Length != b.Length)
{
return false;
}
var aFrequency = CalculateFrequency(a);
var bFrequency = CalculateFrequency(b);
foreach (var key in aFrequency.Keys)
{
if (!bFrequency.ContainsKey(key)) return false;
if (aFrequency[key] != bFrequency[key]) return false;
}
return true;
}
private Dictionary<char, int> CalculateFrequency(string input)
{
var frequency = new Dictionary<char, int>();
foreach (var c in input)
{
if (!frequency.ContainsKey(c))
{
frequency.Add(c, 0);
}
++frequency[c];
}
return frequency;
}