Isomorphic Strings

By | September 2, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

leetcode 205.

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.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Solution. A great solution is from here. It records the position of each char. If position of char are not the same, return false. Each loop will update the position of the char.

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

Check my code on github.