題目:
給定兩個字符串 s 和 t,判斷它們是否是同構的。
如果 s 中的字符可以被替換得到 t ,那麼這兩個字符串是同構的。
所有出現的字符都必須用另一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符可以映射自己本身。
示例 1:
輸入: s ="egg",
t ="add"
輸出: true
示例 2:
輸入: s ="foo",
t ="bar"
輸出: false
示例 3:
輸入: s ="paper",
t ="title"
輸出: true
說明:
你可以假設 s 和 t 具有相同的長度。
python代碼1:
class Solution:
def isIsomorphic(self, s, t):
mapping_dict = {}
for i in range(len(s)):
if s[i] not in mapping_dict:
mapping_dict[s[i]] = t[i]
elif mapping_dict[s[i]] != t[i]:
return False
mapval = [i for i in mapping_dict.values()]
return len(mapval) == len(set(mapval))
python代碼2:
class Solution(object):
def isIsomorphic(self, s, t):
return map(s.find, s) == map(t.find, t)