forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_isomorphic.py
More file actions
47 lines (38 loc) · 1.09 KB
/
is_isomorphic.py
File metadata and controls
47 lines (38 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Isomorphic Strings
Determine if two strings are isomorphic. Two strings are isomorphic if
characters in s can be mapped to characters in t while preserving order,
with a one-to-one mapping.
Reference: https://leetcode.com/problems/isomorphic-strings/description/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def is_isomorphic(s: str, t: str) -> bool:
"""Check if two strings are isomorphic.
Args:
s: Source string.
t: Target string.
Returns:
True if s and t are isomorphic, False otherwise.
Examples:
>>> is_isomorphic("egg", "add")
True
>>> is_isomorphic("foo", "bar")
False
"""
if len(s) != len(t):
return False
mapping: dict[str, str] = {}
mapped_values: set[str] = set()
for i in range(len(s)):
if s[i] not in mapping:
if t[i] in mapped_values:
return False
mapping[s[i]] = t[i]
mapped_values.add(t[i])
else:
if mapping[s[i]] != t[i]:
return False
return True