The complexity of this method is actually \$O(n^2)\$, where \$n\$ is s1.Length
(which is equal to s2.Length
). Let's expand out IndexOf
and see why.
foreach (char c in s1)
{
int ix = -1;
for (var i = 0; i < s2.Length; i++)
{
if (s2[i] == c)
{
ix = i;
break;
}
}
if (ix == -1)
return false;
}
return true;
As @Pimgd pointed out, it is also incorrect. So how can we fix it? Two strings are anagrams if each character occurs the same number of times, so that seems like a likely approach.
Let's write a method to count the occurrences of each character in a string. We'll use a Dictionary<char, int>
to keep track.
private static IDictionary<char, int> GetCharacterCount(string input)
{
var tally = new Dictionary<char, int>();
foreach (var c in input)
{
int count = tally.TryGetValue(c, out count)
? count + 1
: 1;
tally[c] = count;
}
return tally;
}
Now we want to compare the results of this method
var s1Count = GetCharacterCount(s1);
var s2Count = GetCharacterCount(s2);
foreach (var kvp in s1Count)
{
var c = kvp.Key;
if (!s2Count.ContainsKey(c))
{
return false;
}
if (kvp.Value != s2Count[c])
{
return false;
}
}
return true;
Well, that's one approach, but it seems a bit complicated.
Anagrams have another useful properly, which is that two strings are anagrams of each other if and only if they are equal when they are sorted. So let's convert that into code.
To sort a string, we first have to convert it into a character array, sort the array, and then convert back into a string.
private static string Sort(string input)
{
var chars = input.ToCharArray();
Array.Sort(chars);
return new string(chars);
}
Now we can compare the two sorted sorted strings
var s1Sorted = Sort(s1);
var s2Sorted = Sort(s2);
return s1Sorted == s2Sorted;
n
multiplier. \$\endgroup\$return (stringToArray(s1).sort().mergeToString() === stringToArray(s2).sort().mergeToString());
\$\endgroup\$