Check anagrams Algorithm

By   Tewodros   Date Posted: Oct. 2, 2021  Hits: 866   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given two string s1 and s2, we want to  check if one can be reproduced by permutating the chars of the others.

Example:

Given  s1 = "race"  and    s2 = "care"  Ans = true

Given  s1 = "heart"  and    s2 = "earth"  Ans = true

 Given  s1 = "test"  and    s2 = "set"  Ans = false

Solution:

First we can check the length of each string and if they are not the same we can return false.

Then we can throw both chars of each string into a dictionary the chars as a key and the count of each occurrence of chars as a value. 

Then we can iterate through one of the dictionary and check if the values (count of chars) matches for each key (char in the string)

public static bool CheckPermutation (string s1, string s2)    {

           if (s1.Length != s2.Length) return false;

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

           Dictionary<char, int> dict2 = new Dictionary<char, int>();

 

           foreach (char c in s1) {

               if (!dict.ContainsKey(c))                

                   dict.Add(c, 0);                

               else                

                   dict[c]++;                

           }

           foreach (char c in s2) {

               if (!dict2.ContainsKey(c))                

                   dict2.Add(c, 0);                

               else                

                   dict2[c]++;                

           }

           foreach (KeyValuePair<char, int> kv in dict)  {

               if (!dict2.ContainsKey(kv.Key))                

                   return false;                

               else                

                   if (kv.Value != dict2[kv.Key])

                       return false;

           }

           return true;

       }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* wtzofk

Back to Top