美文网首页
205. Isomorphic Strings

205. Isomorphic Strings

作者: April63 | 来源:发表于2018-05-18 10:59 被阅读0次

竟然这样ac了,我只是试了一下。。。想法就是对于每一个字符串都建立一个哈希表,统计他们各个字母的数量,对于相同位置上的字母,两个字符串对于字母数量是一样的,但这样还可能出现abab 和 aabb这种情况,因此还要加上一条判断相邻位置上字母是否相等:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(t) != len(s):
            return False
        dic1 = {}
        dic2 = {}
        i = 0
        while i < len(s):
            if s[i] not in dic1:
                dic1[s[i]] = 1
            else:
                dic1[s[i]] += 1
            if t[i] not in dic2:
                dic2[t[i]] = 1
            else:
                dic2[t[i]] += 1
            i += 1
        
        for i in range(len(s)):
            if dic1[s[i]] != dic2[t[i]]:
                return False
            if i > 0 and s[i] == s[i-1] and t[i] != t[i-1]:
                return False
            if i > 0 and s[i] != s[i-1] and t[i] == t[i-1]:
                return False
        return True

网上提供的做法有很多种,其中一种是建立一个s到t映射的哈希表,最后考虑去重:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(t) != len(s):
            return False
        dic = {}
        for i in range(len(s)):
            if s[i] not in dic:
                dic[s[i]] = t[i]
            else:
                if dic[s[i]] != t[i]:
                    return False
        m = [dic[k] for k in dic]
        return len(m) == len(set(m))
                

相关文章

  • 205. Isomorphic Strings

    205. Isomorphic Strings 题目:https://leetcode.com/problems/...

  • 2019-01-21

    LeetCode 205. Isomorphic Strings Description Given two st...

  • 205. Isomorphic Strings

    https://leetcode.com/problems/isomorphic-strings/descript...

  • 205. Isomorphic Strings

    Problem Given two strings s and t, determine if they are ...

  • 205. Isomorphic Strings

    竟然这样ac了,我只是试了一下。。。想法就是对于每一个字符串都建立一个哈希表,统计他们各个字母的数量,对于相同位置...

  • 205. Isomorphic Strings

    题目分析 原题链接,登录 LeetCode 后可用这道题目让我们判断两个字符串是否是同构字符串。示例如下: 解题思...

  • 205. Isomorphic Strings

    Given two strings s and t, determine if they are isomorph...

  • 205. Isomorphic Strings

    Given two stringssandt, determine if they are isomorphic....

  • 205. Isomorphic Strings

    首先考虑corner case,这题两个空字符返回算True…… 从左到右扫,映射关系存为字典。 如果左边扫到重复...

  • 205. Isomorphic Strings

    问题 Given two strings s and t, determine if they are isomo...

网友评论

      本文标题:205. Isomorphic Strings

      本文链接:https://www.haomeiwen.com/subject/rvawdftx.html