Strings: Making Anagrams

  • + 0 comments

    C#

    public static int makeAnagram(string a, string b)
        {
            Dictionary<char, int> aMap = new();
            Dictionary<char, int> bMap = new();
            int charsToDelete = 0;
            
            for(int i = 0; i < a.Length; i++)
            {
                if(!aMap.TryAdd(a[i], 1))
                {
                    aMap[a[i]] += 1;
                }
            }
            
            for(int j = 0; j < b.Length; j++)
            {
                if(!bMap.TryAdd(b[j], 1))
                {
                    bMap[b[j]] += 1;
                }
            }
            
            foreach(char key in aMap.Keys)
            {
                int aCount = aMap[key];
                int bCount = 0;
                bMap.TryGetValue(key, out bCount);
                
                charsToDelete += Math.Abs(aCount - bCount);
            }
            
            foreach(char key in bMap.Keys)
            {
                int bCount = bMap[key];
                int aCount = 0;
                aMap.TryGetValue(key, out aCount);
                
                if(aCount == 0)
                {
                    charsToDelete += Math.Abs(bCount);
                }
                
            }
            
            return charsToDelete;
        }