0205-isomorphic-strings¶
Try it on leetcode
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.
Example 1:
Input: s = "egg", t = "add"
Output: true
Explanation:
The strings s and t can be made identical by:
- Mapping
'e'to'a'. - Mapping
'g'to'd'.
Example 2:
Input: s = "f11", t = "b23"
Output: false
Explanation:
The strings s and t can not be made identical as '1' needs to be mapped to both '2' and '3'.
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
1 <= s.length <= 5 * 104t.length == s.lengthsandtconsist of any valid ascii character.
Solution(Python)¶
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# not same length false
# mapping s -> t
# in s
# if s already in mapping amd mapping s != t false
# s -> t
# if len(s) != len(t):
# return False
# mapping = {}
# reverse_mapping = {}
# n = len(s)
# for i in range(n):
# if (s[i] in mapping and mapping[s[i]] != t[i]) or (t[i] in reverse_mapping and reverse_mapping[t[i]] != s[i]):
# return False
# mapping[s[i]] = t[i]
# reverse_mapping[t[i]] = s[i]
# return True
return self.transformString(s) == self.transformString(t)
def transformString(self, s: str) -> str:
index_mapping = {}
new_str = []
for i, c in enumerate(s):
if c not in index_mapping:
index_mapping[c] = hash(i)
new_str.append(str(index_mapping[c]))
return " ".join(new_str)