Description

Given two strings s and t, determine if they are isomorphic.

Two strings s and t are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
char_index_s = {}
char_index_t = {}

for i in range(len(s)):
if s[i] not in char_index_s:
char_index_s[s[i]] = i

if t[i] not in char_index_t:
char_index_t[t[i]] = i

if char_index_s[s[i]] != char_index_t[t[i]]:
return False

return True
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

n = [1]*len(s)
m = [1]*len(t)
for i in range(len(s)):
for j in range(i-1,-1,-1):
f = False
if s[j] == s[i]:
n[i] = n[j]+1
f = True
if t[j] == t[i]:
m[i] = m[j]+1
f = True
if f:
break
flag = True
for k in range(len(s)):
if n[k] != m[k]:
flag = False

return flag