C# solution with dictionary


  • 0
    W

    a simply and straight forward solution

    public class Solution {
        public bool IsAnagram(string s, string t) {
            if(s.Length!=t.Length)
            return false;
            
            char[] char_s = s.ToCharArray();
            char[] char_t = t.ToCharArray();
            
            Dictionary<char, int> alphabet = new Dictionary<char, int>();
            for(int i=0;i<char_s.Length;i++)
            {
                if(alphabet.ContainsKey(char_s[i]))
                    alphabet[char_s[i]]+=1;
                else
                    alphabet.Add(char_s[i],1);
            }
            
            for(int i=0;i<char_t.Length;i++)
            {
                if(alphabet.ContainsKey(char_t[i]))
                    {
                    alphabet[char_t[i]]-=1;
                    if (alphabet[char_t[i]]<=0)
                    alphabet.Remove(char_t[i]);
                    }
                else
                    return false;
            }
            
            if (alphabet.Count==0)
            return true;
            else
            return false;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.