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’

Example


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'.


Kotlin program to Check if two given strings are isomorphic


import java.util.HashMap

fun isIsomorphic(s: String?, t: String?): Boolean {
    if (s == null || t == null)
        return false

    if (s.length != t.length)
        return false

    val map = HashMap<Char, Char>()

    for (i in 0 until s.length) {
        val c1 = s[i]
        val c2 = t[i]

        if (map.containsKey(c1)) {
            if (map[c1] != c2)
            // if not consistant with previous ones
                return false
        } else {
            if (map.containsValue(c2))
            //if c2 is already being mapped. Time complexity O(n) here
                return false
            map[c1] = c2
        }
    }
    return true
}

fun main(args: Array<String>) {
    if(isIsomorphic("Madam", "liril")){
        println("string is Isomorphic")
    }else{
        println("string is NOT Isomorphic")
    }
}


Output


string are NOT Isomorphic

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions