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

Example 2:
Input: s = "foo", t = "bar"
Output: false

Example 3:
Input: s = "paper", t = "title"
Output: true

Constraints:

  • 1 <= s.length <= 5 * 10^4
  • t.length == s.length
  • s and t consist of any valid ascii character.

Solution in python:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        length = len(s)
        dic1, dic2 = dict(), dict()
        for i in range(length):
            if (s[i] not in dic1.keys()) and (t[i] not in dic2.keys()):
                dic1[s[i]] = t[i]
                dic2[t[i]] = s[i]
            elif (s[i] not in dic1.keys()) or (t[i] not in dic2.keys()):
                return False
            elif (dic1[s[i]] != t[i]):
                return False
        return True
最后修改日期: 2021年1月19日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。