Check whether two Strings are anagram of each other

An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.

public class Solution
{

    bool AreAnagrams(string str1, string str2)
    {
        if (str1.Length != str2.Length)
            return false;

        var dict = new Dictionary<char, int>();

        foreach (char c in str1)
        {
            if (dict.ContainsKey(c))
                dict[c]++;
            else
                dict[c] = 1;
        }

        foreach (char c in str2)
        {
            if (!dict.ContainsKey(c))
                return false;

            if (--dict[c] == 0)
                dict.Remove(c);
        }

        return dict.Count == 0;
    }
}

With out dictionary, but need to crate a copy from string to char array.


public class Solution {
    public bool IsAnagram(string s, string t) {
         if (s.Length != t.Length)
    return false;

var charsS = s.ToArray();
var charsT = t.ToArray();

Array.Sort(charsS);
Array.Sort(charsT);

for (int i = 0; i < t.Length; i++)
{
    if (charsS[i] != charsT[i])
    {
        return false;
    }
}

return true;
    
    }
}

Last updated