DEV Community

shine
shine

Posted on

[📝LeetCode #205] Isomorphic Strings

🎀 The Problem

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

Example:

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

Explanation: The strings s and t can be made identical by:
Mapping 'e' to 'a'.
Mapping 'g' to 'd'.

👩‍💻 My Answer

class Solution {
    public boolean isIsomorphic(String s, String t) {
        HashMap<Character, Character> map = new HashMap();

        for (int i = 0; i < s.length(); i++) {
            if (!map.containsKey(s.charAt(i)) && !map.containsValue(t.charAt(i)))
                map.put(s.charAt(i), t.charAt(i));
            else if (map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) != t.charAt(i))
                return false;
            else if (!map.containsKey(s.charAt(i)) && map.containsValue(t.charAt(i)))
                return false;
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • ✖️ Runtime & Memory

💋 Ideal Answer

Approach

I was not sure, and I am not sure why my code takes a long time, although I use a HashMap. My favorite YouTuber also suggested the HashMap. Nikhil Lohia's Isomorphic Strings (LeetCode 205)

In LeetCode, I found that the array method is faster than HashMap, so I would try with this array method.

New Code

class Solution {
    public boolean isIsomorphic(String s, String t) {
        int[] slist = new int[256];
        int[] tlist = new int[256];

        for (int i = 0; i < s.length(); i++) {
            if (slist[s.charAt(i)] != tlist[t.charAt(i)])
                return false;

            slist[s.charAt(i)]=i+1;
            tlist[t.charAt(i)]=i+1;
        }

        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

💡 What I Learned

  • Why int[256]? A char in Java is 16-bit, but standard ASCII characters only use 7 bits (0-127).

Extended ASCII uses 8 bits (0-255), so int[256] covers all possible ASCII characters.

  • i + 1 avoids ambiguity with default 0.

Top comments (0)