Check if two given strings are isomorphic to each other in C# – Geeksforgeeks

Problem source: http://www.geeksforgeeks.org/check-if-two-given-strings-are-isomorphic-to-each-other/

Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1′ map to same character in ‘str2′

Examples:

Input:  str1 = "aab", str2 = "xxy"
Output: True
'a' is mapped to 'x' and 'b' is mapped to 'y'.

Input:  str1 = "aab", str2 = "xyz"
Output: False
One occurrence of 'a' in str1 has 'x' in str2 and 
other occurrence of 'a' has 'y'.

Algorithm: 
1. Check both the string are equal in length or not. If not then return false 
(not Isomorphiic).
2. Create a Generic Dictionary of Key/value pair Character type.
3. Think of first string as array of keys and corresponding each item of this 
   array there will be a value in string 2.
4. Check item of str1 exists in dictionary or not as key. If not exists then insert 
   a new item (key: str1[i], value: str2[i])
5. If item exists then check for the value of current key, if it doesn't match with 
   str2[i] that means strings are not Isomorphic, return false. 

 

class IsomorphicStrings
{
static void Main(string[] args)
{
string strInput1 = Console.ReadLine();
string strInput2 = Console.ReadLine();
Console.WriteLine(IsIsomorphicStrings(strInput1, strInput2) ? “Strings are Isomorphic.” : “Strings are not Isomorphic.”);
Console.ReadKey();
}

static bool IsIsomorphicStrings(string str1, string str2)
{
if (str1.Length != str2.Length)
{
return false;
}
else
{
Dictionary<char, char> dict = new Dictionary<char, char>();
for (int i = 0; i < str1.Length; ++i)
{
if (!dict.ContainsKey(str1[i]))
{
dict.Add(str1[i], str2[i]);
}
else
{
if (dict[str1[i]] != str2[i])
{
return false;
}
}
}
}
return true;
}
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s