In this Leetcode Isomorphic Strings problem solution we have Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Leetcode Isomorphic Strings problem solution


Problem solution in Python.

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        X=[]
        Y=[]
        for i in s:
            X.append(s.index(i))
        for i in t:
            Y.append(t.index(i))
        if X==Y:
            return True
        return False



Problem solution in Java.

class Solution {
    public boolean isIsomorphic(String s, String t) {

         if (s.length() != t.length()) {
            return false;
        }

     return (checkIsoMorphism(s,t) && checkIsoMorphism(t,s));

    }

    private static boolean checkIsoMorphism(String s,String t)
    {
        HashMap<Character, Character> charMap = new HashMap<>();
        boolean result = true;
        for (int i = 0; i < s.length(); i++) {
            if (!charMap.containsKey(s.charAt(i)))
                charMap.put(s.charAt(i), t.charAt(i));
            else {
                if (!((charMap.get(s.charAt(i))) == t.charAt(i))) {
                    
                    result = false;
                    break;

                }

            }
        }

        return(result);
    }
}


Problem solution in C++.

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        return (isIso(s,t) && isIso(t,s));
    }
    bool isIso(string &s, string &t) {
        unordered_map<char, char> m;
        int l = s.length();
        for(int i=0;i<l;i++){
            if(m.count(s[i])) {
                if(m[s[i]] != t[i]) {
                    return false;
                }
            } else {
                m[s[i]]=t[i];
            }
        }
        return true;
    }
};


Problem solution in C.

bool isIsomorphic(char* s, char* t) {
    int s2t[256] = {0};
    int t2s[256] = {0};
    for(; *s != '\0'; s++,t++)
    {
        if(s2t[*s] == 0)
        {
            if(t2s[*t] != 0)
            {
                return false;
            }
            s2t[*s] = *t;
            t2s[*t] = *s;
        }
        else if(s2t[*s] != *t){
            return false;
        }
    
    }
    return true;
 }