Isomorphic Strings Algo

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


side

Given to string s1 and s2, we want to check if they are isomorphic strings. Two string are Isomorphic when there exists a one to one mapping between each character of both string.

Example.

Consider s1 = abefbctba and s2 = ghtdhdshg

Ans. True.

S1S2
ag
bh
et
fd
bh
cd
ts
bh
ag

 

Example.

Consider s1 = abefbctba and s2 = ghtdhdsfg

Ans. False as the last b in s1 is not approprtely mapped to h in s2. S2 has f instead. 

Solution:

This problem can easily be solved using a dictionary data structure as it is efficient in dealing with key value pairs like we saw in the above table.

All we have to do is store the characters of s1 in the dictionary using the above mapping (s1 as key, s2 as value)  if it is not added yet.

If it is already there that means we can get the value using the key (s1) and compare it with what is in there in s2 and it doesn't match, bingo!!! It means they are not Isomorphic strings.

 

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

              int i = 0;

              foreach(char c in s1)

               {

                   if(!dict .ContainsKey(c))

                     dict .Add(c, s2[i]);                

                   else if (dict [c]!=s2[i])

                       return false;

                   i++;

               }

               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:* pxkjxr

Back to Top