205. Isomorphic Strings ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Hash Table
, String
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
.
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:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
1 <= s.length <= 5 * 10^4
t.length == s.length
s
and t
consist of any valid ASCII character.
To determine if two strings are isomorphic, we need to map characters from s
to t
while ensuring no two characters from s
map to the same character in t
(and vice versa).
Create Two Maps:
sToT
to map characters from s
to t
.
tToS
to map characters from t
to s
.
Iterate Through Both Strings:
For each character in s
and t
:
Check if the mappings are consistent in both directions.
If not, return false
.
Result:
If all character mappings are consistent, return true
.
O(n):
n
is the length of the strings.
Each character is visited once.
O(1):
Fixed space for the hash maps since the character set is limited (ASCII).
You can find the full solution .