Isomorphic Strings

Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"
Output: true

  e → a
  g → d
  g → d

Example 2:

Input: s = "foo", t = "bar"
Output: false

  f  → b
  o  → a
  o  → r

You may assume both and have the same length.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if (s == null && t == null) return true;
        if (s.length() == 0 && t.length() == 0) return true;
        if (s == null || t == null) return false;
        Map<Character, Character> map = new HashMap<>();
        Set<Character> uniqueT = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            char fromS = s.charAt(i);
            char fromT = t.charAt(i);
            Character mapping = map.get(fromS);
            if (mapping == null) {
                if (uniqueT.contains(fromT)) return false;
                map.put(fromS, fromT);

            } else if (!mapping.equals(fromT)) return false;
        return true;

Categories: String

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s