205. Isomorphic Strings
Содержание
Use two dictionaries to track the mappings from s
to t
and from t
to s
. This helps in ensuring no two characters map to the same character.
- Key Idea: To verify if two strings are isomorphic, we need to ensure that each character in s maps to a unique character in t, and vice versa. This bi-directional mapping is crucial to maintain the isomorphism property.
- Data Structures: Two hash maps (or dictionaries in Python) are ideal for maintaining these mappings efficiently.
Approach
- Initial Checks: If the lengths of
s
andt
are different, they cannot be isomorphic. Return false immediately. - Create Two Mappings: Initialize two dictionaries. One for mapping characters from
s
tot
(s_to_t
) and another fromt
tos
(t_to_s
). - Iterate Over Characters:
- For each character pair (
s_char
,t_char
) ins
andt
, check:- If
s_char
maps to a differentt_char
ins_to_t
, ort_char
maps to a differents_char
int_to_s
, return false. - Update
s_to_t[s_char] = t_char
andt_to_s[t_char] = s_char
.
- If
- Return True: If the loop completes without returning false, then
s
andt
are isomorphic.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
s_to_t, t_to_s = {}, {}
for s_char, t_char in zip(s, t):
if (s_char in s_to_t and s_to_t[s_char] != t_char) or \
(t_char in t_to_s and t_to_s[t_char] != s_char):
return False
s_to_t[s_char] = t_char
t_to_s[t_char] = s_char
return True