LeetCode - Isomorphic Strings

Given two strings s and t, determine whether they are isomorphic.

If the characters in s can be replaced to give t, then the two strings are isomorphic.

All occurrences of characters must be replaced with another character while preserving the order of the characters. Two characters cannot map to the same character, but a character can map itself.

Example 1:

Input: s = "egg", t = "add"
Output: true
Example 2:

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

class Solution:
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic = {}                                
        i = 0
        while i < len(s):
            if s[i] not in dic:
                if t[i] in dic.values():
                    return False
                dic[s[i]] = t[i]
            else:
                if dic[s[i]] != t[i]:
                    return False
            i += 1
        return True

The topic has already suggested that there is a mapping relationship between two strings.
Use a dictionary to receive the mapping relationship between two strings.

if s[i] not in dic:
    if t[i] in dic.values():
        return False
    dic[s[i]] = t[i]

If s[i] is not in dic, but t[i] is already in dic's values, return False
if s[i] is not in dic, t[i] is not in dic's values, add the new mapping relationship to the dictionary

else:
    if dic[s[i]] != t[i]:
        return False

If s[i] is in the dictionary, but the corresponding value that already exists in the dictionary is not equal to t[i], return False.
If there is no return after the sequence is executed, it indicates that the mapping relationship is established and returns True

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568699&siteId=291194637