Understanding isomorphic strings algorithm

后端 未结 4 1258
梦谈多话
梦谈多话 2021-01-27 08:15

I am understanding the following code to find if the strings are isomorphic or not. The code uses two hashes s_dict and t_dict respectively. I am assum

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 08:56

    Here is a solution for Isomorphic String problem in Python:

    Solution #1 (the fastest one):

    def isometric_strings_translate(str1: str, str2: str) -> bool:
        trans = str.maketrans(str1, str2)
        return str1.translate(trans) == str2
    

    Solution #2 (using set):

    def isometric_strings_set(str1: str, str2: str) -> bool:
        return len(set(zip(str1, str2))) == len(set(str1))
    

    Solution #3 (using dictionary):

    def isometric_strings_dict(str1: str, str2: str) -> bool:
        map = {}
        for s1, s2 in zip(str1, str2):
            if map.setdefault(s1, s2) != s2:
                return False
        return True
    

    Here you can view full code.

提交回复
热议问题