Skip to content

Commit a75477f

Browse files
authored
Create string mapping.py
1 parent 87dfb4c commit a75477f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

interview_query/string mapping.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'''
2+
Given two strings, string1 and string2, write a function str_map to determine if there exists
3+
a one-to-one correspondence (bijection) between the characters of string1 and string2.
4+
5+
For the two strings, our correspondence must be between characters in the same position/index.
6+
'''
7+
8+
9+
from collections import Counter
10+
11+
def str_map(string1, string2):
12+
13+
if len(string1)!= len(string2):
14+
return False
15+
16+
d = Counter(string1)
17+
d2 = Counter(string2)
18+
19+
for k,v in d.items():
20+
if d2[k] !=v:
21+
return False
22+
return True
23+
24+
-------------------------------------------------------------------------------------------------------
25+
def str_map(string1, string2):
26+
# check whether the strings are the same length
27+
if len(string1) != len(string2):
28+
return False
29+
30+
char_map = dict()
31+
for char1, char2 in zip(string1, string2):
32+
if char1 not in char_map:
33+
char_map[char1] = char2
34+
elif char_map[char1] != char2:
35+
return False
36+
for char1, char2 in zip(string2, string1):
37+
if char1 not in char_map:
38+
char_map[char1] = char2
39+
elif char_map[char1] != char2:
40+
return False
41+
42+
return True
43+
44+
45+

0 commit comments

Comments
 (0)