I just started going through "Cracking the Coding Interview" and have the following solution for this problem:
public static bool isAnagram(String s, String t)
{
if (s == "" || t == "") return false;
else if (s.Length != t.Length) return false;
int[] letters = new int[256];
char[] s_array = s.ToCharArray();
foreach(char c in s_array)
{
letters[c]++;
}
for (int i = 0; i < t.Length; i++)
{
int c = t[i];
if (--letters[c] < 0)
{
return false;
}
}
return true;
}
This is pretty much the verbatim solution from the book, only in C#, not Java, and with some additional nullchecks. I also solved the question using LINQ but wanted an additional solution that didn't involve sorting.
Can this approach be made a bit more elegant? The code works just fine, I just want to know if there is a more elegant or better solution out there. Thanks!!