LeetCode 205. 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

Example 2:

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

Example 3:

Input: s = "paper", t = "title"
Output: true

You may assume both and have the same length.

One way is to traverse the characters in string s, every time we meet a unique character, we use the character in the same position in string t. One by one, when we finish if the two strings are identical, then they are isomorphic. But I think this way is too complex.

So we use another way. We use a hashmap to restore the first time occurs of every unique character. Then we output the index to an array, so we get a pattern array of a string.

Like example 1, we can get the pattern array of “egg” as [0,1,1]. And the pattern array of “add” is [0,1,1] too. So “egg” and “add” are isomorphic.

“foo” from example 2, its pattern array is [0,1,1]. But bar’s pattern array is [0,1,2]. So they are not isomorphic.

The first part of the code is how to transform a string to a pattern array:

The second part compares the two pattern array is identical or not.


To see more hashtable related problems, see 
Problems and Solutions of Hashmap.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.