205. Isomorphic Strings

Overview
If the two input strings have same character orders, they are isomorphic strings.
Solution 1: Hash Table
Thinking
Use two hash tables, one to save s mapped to t and another to save t mapped to s.
Check if the character showing next time is the same as the first pair.
Algorithm
-
Initialize two hash tables to save
smapped totandtmapped tos. -
Iterate through strings
sandt:- If
char_sexists ins_to_tandchar_tis not equal tos_to_t[char_s], returnfalse. - If
char_texists int_to_sandchar_sis not equal tot_to_s[char_t], returnfalse. - Otherwise, set
s_to_t[char_s]tochar_tand sett_to_s[char_t]tochar_s.
- If
-
If all pairs are correct,
sandtare isomorphic strings, returntrue.
Implement
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: s_to_t: dict[str, str] = {} t_to_s: dict[str, str] = {} for char_s, char_t in zip(s, t): if char_s in s_to_t: if char_t != s_to_t[char_s]: return False elif char_t in t_to_s: if char_s != t_to_s[char_t]: return False else: s_to_t[char_s] = char_t t_to_s[char_t] = char_s return True
Complexity Analysis
Time complexity: O(n)
Iterating through strings s and t takes O(n) time.
Space complexity: O(n)
Using two additional hash tables takes O(2n) time, which simplifies to O(n).