Leetcode 205. Isomorphic Strings

January 1, 2022

205. Isomorphic Strings

Result

Runtime: 7 ms, faster than 90.80% of Java online submissions for Isomorphic Strings. Memory Usage: 42.5 MB, less than 82.34% of Java online submissions for Isomorphic Strings.

class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> fromTo = new HashMap<>();
        // we make sure that there are not several translations into the same charachter
        Map<Character, Character> toFrom = new HashMap<>();
        
        for(int i=0; i<s.length(); i++) {
            if(fromTo.get(s.charAt(i)) == null && toFrom.get(t.charAt(i)) == null) { 
                fromTo.put(s.charAt(i), t.charAt(i));
                toFrom.put(t.charAt(i), s.charAt(i));
            }
        }
        for(int i=0; i<s.length(); i++) {
            if(fromTo.get(s.charAt(i)) == null)
                return false;
            if(fromTo.get(s.charAt(i)) != t.charAt(i))
                return false;
        }
        return true;
    }
}