Python实现"同构字符串"的两种方法

给定两个字符串 和 t,判断它们是否是同构的

如果 中的字符可以被替换得到 ,那么这两个字符串是同构的

所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身

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

注意:

你可以假设字符串s和t等长

1:该题只要判断两个字符串是不是同一种形式,可以借助字典(键值对为character:value)分别将字符串转换成数值数组(“egg”为[1,2,2]),然后判断两个字符串是否相等

def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        sDic = {}       #存放s字符串中所有不重复的字符,存储格式为cha:value
        sStr = []       #存放字符串对应的数值表示,如"egg"转换之后为[1,2,2]
        tDic = {}       #如上
        tStr = []
        count = 1
        for i in s:     #转换s字符串
            if i not in sDic:
                sDic[i] = count
                sStr.append(sDic[i])
                count += 1
            else:
                sStr.append(sDic[i])
        count = 1
        for i in t:     #转换t字符串
            if i not in tDic:
                tDic[i] = count
                tStr.append(tDic[i])
                count += 1
            else:
                tStr.append(tDic[i])
        return sStr==tStr     #判断字符串s和t转换成链表之后是否相等

2:利用len()、set()和zip()方法(参考他人)

    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return len(set(s))==len(set(t))==len(set(zip(s, t)))

算法题来自:https://leetcode-cn.com/problems/isomorphic-strings/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82780935