1. Problem
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.
2. Solution
2.1. Using dictionary
I solve this problem like this. I added key and value of dictionary.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
dic = {}
for _s, _t in zip(s, t):
dic[_s] = _t
for _s, _t in zip(s, t):
if dic[_s] != _t:
return False
dic = {}
for _s, _t in zip(s, t):
dic[_t] = _s
for _s, _t in zip(s, t):
if dic[_t] != _s:
return False
return True
2.2. Using index
I confirmed other user’s solution.
He solved this problem like under code.
- Check the character is in string and add index in list.
- Check two index list value is same.
# Time Complexity : O(n)
class Solution(object):
def isIsomorphic(self, s, t):
map1 = []
map2 = []
for idx in s:
map1.append(s.index(idx))
for idx in t:
map2.append(t.index(idx))
if map1 == map2:
return True
return False
This solution can be shorten like under code.
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)]