LeetCode-Python-242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

第一种思路:

排序比较。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sorted(s) == sorted(t)

第二种思路:

用hashmap分别统计两个字符串中字符出现的次数,然后比较hashmap

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        hashmaps, hashmapt = dict(), dict()
        for char in s:
            hashmaps[char] = hashmaps.get(char, 0) + 1
        
        for char in t:
            hashmapt[char] = hashmapt.get(char, 0) + 1
            
        return hashmaps == hashmapt
        

下面的写于2019年8月16日22:01:23

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        from collections import Counter
        return Counter(s) == Counter(t)

 


版权声明:本文为qq_32424059原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。