Accepted Java solution with one HashMap


  • 0
    J
    public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length()!=t.length()) return false;
        HashMap<Character, Character> pairs = new HashMap<Character, Character>();
        int len=s.length();
        for(int i=0; i<len; i++){
            char first=s.charAt(i);
            char second=t.charAt(i);
            if(!pairs.containsKey(first) ) {
                if(!pairs.containsValue(second)){//if doesnt contain the key
                pairs.put(first, second);
                }else{
                    return false;
                }
        }else{//if contains the key
            if(pairs.get(first)==second){//check whether it is the correct key-value pair
                continue;
            }else{
                return false;
            }
        }
    }
    return true;
    }
    

    }


  • 0
    P

    I am very comfortable with this solution.


  • 0
    L

    One thing to note is that containsKey is O(1) while containsValue is O(n).


  • 0
    This post is deleted!

Log in to reply
 

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