Isomorphic Strings

 Isomorphic Strings

Sergei Golitsyn

https://leetcode.com/problems/isomorphic-strings/

Given two strings s and tdetermine if they are isomorphic.

Two strings s and t 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

Example 2:

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

Example 3:

Input: s = "paper", t = "title"
Output: true
  • s and t consist of any valid ASCII character.


Solution:

To solve this problem, we must map chars from one string to another. How can we do it? For example, we can use two maps and map 'a' to 'b' and 'b' to 'a'. Yeah, it will work. But do you know how many links and additional memory we will use for it?

On the other side, we know that we will have only ASCII characters in this problem. How can we use it? We can create two dictionaries on 256 characters and use them.

  public boolean isIsomorphic(String s, String t) {

    int[] sChar = new int[256];
    int[] tChar = new int[256];
    Arrays.fill(sChar, -1);
    Arrays.fill(tChar, -1);

    for(int i = 0; i < s.length(); i++){
      int sCharIdx = s.charAt(i);
      int stCharIdx = t.charAt(i);
      if (sChar[sCharIdx] == -1 && tChar[stCharIdx] == -1){
        sChar[sCharIdx] = stCharIdx;
        tChar[stCharIdx] = sCharIdx;
      } else if (sChar[sCharIdx] != stCharIdx 
                || tChar[stCharIdx] != sCharIdx) {
        return false;
      }
    }
    return true;
  }

Report Page