LeetCode #205 Isomorphic Strings

Easy

Len Chen
1 min readOct 2, 2018

Problem

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

Note:
You may assume both s and t have the same length.

Solution

Use two extra hash maps to maintain mapping relations between two strings.

complexity

It takes O(n) time to iterate s and t if n denotes to the length of these two lists. In each iteration, search and insert operations of hash map will take O(1)/O(logn) time in average/worst cases. Thus, the time complexity will be O(n)/O(nlogn) in average/worst cases.

Besides, because there are two hash maps, it’s space complexity is O(n + n) = O(n).

--

--

Len Chen
Len Chen

No responses yet