Simple Java Solution with one HashMap


  • 1
    C
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            // check invalid inputs;
            if(s==null&&t==null)
                return true;
            if(s==null||t==null)
                return false;
            if(s.length()!=t.length())
                return false;
            Map<Character,Character> hm= new HashMap<Character,Character>();
            for(int i=0;i<s.length();i++){
                Character sChar = s.charAt(i);
                Character tChar = t.charAt(i);
                if(hm.containsKey(sChar)){   // if map already contains key make sure value is the same 
                    if(hm.get(sChar)!=tChar)
                        return false;
                }else if(hm.containsValue(tChar)){ // if map doesn't contain the key make sure it doesn't already contain the value
                    return false;
                }else{   // otherwise insert key, value pair
                    hm.put(sChar,tChar);
                }
            }
            return true;
        }
    }

Log in to reply
 

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