A java implementation from a layman 26ms


  • 0
    A

    public class Solution {
    public boolean isIsomorphic(String s, String t) {
    HashMap<Character, Character> hm = new HashMap<Character, Character>();

        //if length is not same, strings cannot be isomorphic
        if(s.length() != t.length())
            return false;
        
        //iterate over all characters of a string
        for(int i=0 ; i<s.length() ; i++)
        {
            //check if hashmap already contains the key value pair
            if(hm.containsKey(s.charAt(i)))
            {
                //if yes, compare the character at the same index in other string to value in hashmap
                if(t.charAt(i) != hm.get(s.charAt(i)))
                    return false;
            }
            else
            {
                //check if character at the same index in other string is already stored in the hashmap
                if(hm.containsValue(t.charAt(i)))
                        //if yes, return false
                        return false;
                //or add the new key value pair in hashmap since its unique
                hm.put(s.charAt(i), t.charAt(i));
            }
        }
        
        return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.