Isomorphic Strings
- 1 min read
- String
- LC-Easy
Solution
- Maintain a mapping from s to t and then from t to s.
- When a character was already mapped and then the character it maps to is different from the character it was previously mapped to, return False immediately.
- If end of code is reached, return True.
- Similar to Word Pattern
| Time | Space | Explanation |
|---|
O(n) | O(n) | |
def isIsomorphic(self, s: str, t: str) -> bool:
s_map = {}
t_map = {}
for i in range(len(s)):
if s[i] not in s_map:
s_map[s[i]] = t[i]
if t[i] not in t_map:
t_map[t[i]] = s[i]
if s_map[s[i]] != t[i] or t_map[t[i]] != s[i]:
return False
return True