Skip to content

Commit b515155

Browse files
committed
add is isomorphic algorithm
1 parent 2ef04d4 commit b515155

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

strings/isomorphic.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
is_isomorphic('foo', 'bar') => False
3+
is_isomorphic('foo', 'bee') => True
4+
complexity: O(n)
5+
"""
6+
7+
8+
def is_isomorphic(base_string: str, string: str) -> bool:
9+
if len(base_string) != len(string):
10+
return False
11+
string_relations = {}
12+
for base_letter, letter in zip(base_string, string):
13+
correct_letter = string_relations.get(base_letter)
14+
if letter in string_relations.values() and correct_letter is None:
15+
return False
16+
if correct_letter is None:
17+
string_relations[base_letter] = letter
18+
continue
19+
if correct_letter != letter:
20+
return False
21+
return True
22+
23+
24+
if __name__ == "__main__":
25+
print(is_isomorphic('foo', 'bar') is False)
26+
print(is_isomorphic('foo', 'bee') is True)
27+
print(is_isomorphic('fow', 'bee') is False)
28+
print(is_isomorphic('paper', 'title') is True)

0 commit comments

Comments
 (0)