leetcode205. 同構字符串

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

如果 s 中的字符可以被替換得到 t ,那麼這兩個字符串是同構的。
所有出現的字符都必須用另一個字符替換,同時保留字符的順序。兩個字符不能映射到同一個字符上,但字符可以映射自己本身。
示例 1:
輸入: s = “egg”, t = “add”
輸出: true
示例 2:
輸入: s = “foo”, t = “bar”
輸出: false
示例 3:
輸入: s = “paper”, t = “title”
輸出: true
說明:
你可以假設 s 和 t 具有相同的長度。

要考慮到s=‘bar’ t=‘foo’的情況:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s_dict, t_set = {}, set()  # s->t,t
        for i in range(len(s)):
            if s[i] in s_dict:
                if s_dict[s[i]] != t[i]:  # 映射不到
                    return False
            elif t[i] in t_set:  # 如果不在dict卻在set
                return False
            else:
                s_dict[s[i]] = t[i]
                t_set.add(t[i])
        return True

也可以用兩個dict

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s_dict, t_dict = {}, {}
        for i in range(len(s)):
            if s[i] not in s_dict:
                s_dict[s[i]] = t[i]
            if t[i] not in t_dict:
                t_dict[t[i]] = s[i]
            if s_dict[s[i]] != t[i] or t_dict[t[i]] != s[i]:
                return False
        return True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章