【算法与数据结构相关】【LeetCode】【205 同构字符串】【Python】

题目:给定两个字符串 和 t,判断它们是否是同构的。如果 中的字符可以被替换得到 ,那么这两个字符串是同构的。所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身

示例:

输入: s = "egg", t = "add"
输出: true
输入: s = "foo", t = "bar"
输出: false
输入: s = "paper", t = "title"
输出: true

思路:根据字符串s构建一个字典,字典中的键为s中的字符,值为该字符在字典中出现的位置,然后用这个字典去检验t,看是否一个键所对应的所有位置均相同。

代码:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)<2:
            return True
        count_dic = {}
        for index,item in enumerate(s):
            if not s.count(item) == t.count(t[index]):
                return False
            if not item in count_dic.keys():
                count_dic[item] = [index]
            else:
                count_dic[item].append(index)
        for item in count_dic:
            tmp = t[count_dic[item][0]]
            for i in range(1,len(count_dic[item])):
                if not t[count_dic[item][i]] == tmp:
                    return False
        return True

运行结果:通过倒是通过了,但是运行时间超长,算法效率太低,1700多毫秒

参考别人的做法:

依然是用s映射到一个字典,步骤同上,但又将字典的值依次添加到一个队列中,最后得到一个队列,可以理解成这个队列是对该字符串的编码,然后对两个字符串的编码做对比即可

代码:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return self.isomorphic(s)==self.isomorphic(t)
    def  isomorphic(self,t):
        s=[]
        d={}
        for i in range(len(t)):
            if t[i] not in d:
                d[t[i]]=i
            s.append(d[t[i]])
        return s

算法耗时只有44ms!!!

猜你喜欢

转载自blog.csdn.net/gq930901/article/details/81915738