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.
s
and t
consist of lowercase English letters, but we can assume they can be any printable ASCII characters unless specified otherwise.s
and t
?
s
and t
be empty? How should such cases be handled?
def isIsomorphic(s: str, t: str) -> bool:
if len(s) != len(t):
return False
mapping_s_to_t = {}
mapping_t_to_s = {}
for char_s, char_t in zip(s, t):
if char_s in mapping_s_to_t:
if mapping_s_to_t[char_s] != char_t:
return False
else:
mapping_s_to_t[char_s] = char_t
if char_t in mapping_t_to_s:
if mapping_t_to_s[char_t] != char_s:
return False
else:
mapping_t_to_s[char_t] = char_s
return True
Initial Check: Begin by checking if the lengths of the two strings are different. If they are, return False
immediately since they can’t be isomorphic.
mapping_s_to_t
: Maps a character from s
to t
.mapping_t_to_s
: Maps a character from t
to s
.s
and t
simultaneously.(char_s, char_t)
, check if there is a mapping already established in either direction.char_s
is already mapped to another character, check if it maps to the current char_t
. If not, return False
.char_t
is already mapped to another character, check if it maps to the current char_s
. If not, return False
.True
as the strings are isomorphic.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?