So I decided to lookup some algorithms, and one of the ones I found was.. "Check if the string is an anagram" and without using Google for more than checking what an anagram is, I decided to write some code.
What the code is doing is that it takes two strings.
car
and arc
for instance, and then it takes the first character from the first string car (c)
and compares it to each character in the 2nd string. If it finds it, it removes both the occurrences at each corresponding index.
Once it finishes the outer loop it checks if the two strings are the same, which if it was an anagram, both strings would equal ""
. And if they are, that means we've successfully found an anagram.
This feels like a super un-optimized version of a very simple problem. I later started Googling for other peoples solution and I quickly noticed that people would just check if they're the same when sorted, which makes a lot of sense. I feel very stupid for not have picked that up while writing the code, and I would of done the same thing if I knew that sorting was an option.
At least I know until next time so it wasn't for nothing. I just feel very silly.
Could someone look at my version and see what's good / bad about it, what could I have done to optimize it without using a sorting algorithm. If it even works 100% of the time and what the time complexity is compared to if you were to sort it for instance.
bool IsAnagram(string s1, string s2)
{
if (s1.Length != s2.Length)
return false;
for (int x = 0; x < s1.Length; x++)
{
var tempChar = s1[x];
for (int y = 0; y <= s2.Length - 1; y++)
{
if (s2[y] == tempChar)
{
s1 = s1.Remove(x, 1);
s2 = s2.Remove(y, 1);
}
}
}
if (s1 == s2)
return true;
return false;
}
"Check if the string is an anagram"
is not an algorithm. Are two strings anagrams? is a problem that may have many abstract solutions. When comparing a pair of algorithms 1 & 2, there may be an aspect a (say, space required with increasing problem site) where 1 is preferable while 2 is better in some other aspect b (say, readability). \$\endgroup\$