Share my JAVA solution using two HashMaps.


  • 0
    F

    map1 and map2 stores the last position where char s(i) and t(i) appeared.
    note that you need to use equals instead of == in the condition expression, by default, == compares address while equals compares values of Integers.

    public boolean isIsomorphic(String s, String t) {
            Map<Character, Integer> map1 = new HashMap<>();
            Map<Character, Integer> map2 = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                char ch1 = s.charAt(i);
                char ch2 = t.charAt(i);
                if (!map1.getOrDefault(ch1, -1).equals(map2.getOrDefault(ch2, -1))) {
                    return false;
                }
                map1.put(ch1, i);
                map2.put(ch2, i);
            }
            return true;
        }
    

  • 0
    A

    @fhqplzj a similar idea, slower but might be easier to read :

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            return onto(s,t) && onto(t,s);
        }
        boolean onto(String s, String t){
            Map<Character,Character> map = new HashMap<>();
            for(int i=0;i<s.length();i++){
                char cs= s.charAt(i), ct = t.charAt(i);
                if(map.containsKey(cs)){
                    if(map.get(cs) != ct) return false;
                } else {
                    map.put(cs, ct);
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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