leetcode之Isomorphic Strings(205)

題目:

給定兩個字符串 和 t,判斷它們是否是同構的。

如果 中的字符可以被替換得到 ,那麼這兩個字符串是同構的。

所有出現的字符都必須用另一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符可以映射自己本身。

示例 1:

輸入: s = "egg", t = "add"
輸出: true

示例 2:

輸入: s = "foo", t = "bar"
輸出: false

示例 3:

輸入: s = "paper", t = "title"
輸出: true

說明:
你可以假設 和 具有相同的長度。

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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章