AC solution in Java

  • 1
    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            int len = s.length();
            Map<Character, Character> mapping = new HashMap<>();
            Set<Character> used = new HashSet<>();
            for (int i = 0; i < len; i++) {
                char mapFrom = s.charAt(i);
                char mapTo = t.charAt(i);
                if (!mapping.containsKey(mapFrom)) {
                    if (used.contains(mapTo)) return false;
                    mapping.put(mapFrom, mapTo);
                } else {
                    if (mapping.get(mapFrom) != mapTo) return false;
            return true;

    The question is essentially asking for a unique 1-to-1 mapping. Therefore, for each pair, we only need to check whether an existing mapping is consistent or a new mapping maps to a unused character.

    public boolean isIsomorphic2(String s, String t) {
        int[] map1 = new int[256];
        int[] map2 = new int[256];
        for (int i = 0; i < s.length(); i++) {
            if (map1[s.charAt(i)] != map2[t.charAt(i)]) return false;
            map1[s.charAt(i)] = map2[t.charAt(i)] = i + 1;
        return true;

    Another way to think about it is that a pair of two characters must map to the same group. Therefore, there are two int arrays to achieve that.

Log in to reply

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