LeetCode 205. isomorphic string (Python)

Topic Link

Subject description:

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

S If the characters can be obtained by replacing t, then the two strings are isomorphic.

All characters appearing must be replaced with another character, while preserving the order of characters. Two characters can not be mapped to the same character, but the character itself can be mapped.

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
Note:
You can assume s and t have the same length

Problem-solving ideas:
each traversal s, t
appear with res stored over the letters with different letters and rr recording order (as will add denoted as 011), flag the letter represents the number of species currently occurring
if the letter is not currently in the res appeared to add to the current letter res, the rr + = flag, flag + 1
if the current letter appears over-res, add the current in the alphabetical index to the back of res rr

def sstr(s):
    res=''
    flag=0
    rr=''
    for i in s:
        if i not in res:
            res+=i
            rr+=str(flag)
            flag+=1
        else:
            rr+=str(res.index(i))
    return rr
    
class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sstr(s)==sstr(t)

Here Insert Picture Description

Comments area answers

        res={}
        if len(s)!=len(t):
            return False
        else:
            for i in range(len(s)):
                if s[i] in res:
                    if res[s[i]]!=t[i]:
                        return False
                else:
                    if t[i] in res.values():
                        return False
                res[s[i]]=t[i]
        return True

Guess you like

Origin blog.csdn.net/weixin_44740082/article/details/91533781