125-242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 (照旧第一个我写的,其他的我抄的.)
class Solution(object):
    def isAnagram1(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        set_s = set(s)
        set_t = set(t)
        if len(s) != len(t) or set_s != set_t:
            return False
        s = sorted(s)
        t = sorted(t)
        return s == t

    def isAnagram2(self, s, t):
        """ 我可能是疯了,我一直感觉count很内存所以没用,我想多了
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        a = set(s)
        for i in a:
            if s.count(i) != t.count(i):
                return False
        return True

    def isAnagram(self, s, t):
        """  实验才是检验真理的唯一标椎
        :type s: str
        :type t: str
        :rtype: bool
        """
        s_dic, t_dic = {}, {}
        for i in s:
            s_dic[i] = s_dic.get(i, 0) + 1

        for i in t:
            t_dic[i] = t_dic.get(i, 0) + 1

        return s_dic == t_dic


if __name__ == '__main__':
    s1 = Solution()
    # s = "rat"; t = "car"
    # s = "anagram"; t = "nagaram"
    # s = "aa"; t = "bb"
    s = "aabbbb"; t="aaaabb"
    print(s1.isAnagram(s, t))
posted @ 2021-01-04 10:45  楠海  阅读(61)  评论(0编辑  收藏  举报