242. 有效的字母异位词

242. 有效的字母异位词

  • 题目-简单难度
  • 1. Counter
  • 2. 排序
  • 3. 字典计数

题目-简单难度

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

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

示例 1:

输入: s = “anagram”, t = “nagaram”
输出: true

示例 2:

输入: s = “rat”, t = “car”
输出: false

提示:

  • 1 <= s.length, t.length <= 5 * 104
  • s 和 t 仅包含小写字母

进阶:

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-anagram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1. Counter

执行用时:48 ms, 在所有 Python 提交中击败了23.10%的用户
内存消耗:13.2 MB, 在所有 Python 提交中击败了53.96%的用户
通过测试用例:40 / 40

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        # 只要用于计数的方法都能完成
        return Counter(s) == Counter(t)

2. 排序

执行用时:48 ms, 在所有 Python 提交中击败了23.10%的用户
内存消耗:14.2 MB, 在所有 Python 提交中击败了24.36%的用户
通过测试用例:40 / 40

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

        return sorted(s) == sorted(t)

3. 字典计数

执行用时:32 ms, 在所有 Python 提交中击败了75.56%的用户
内存消耗:17.6 MB, 在所有 Python 提交中击败了5.17%的用户
通过测试用例:40 / 40

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)!=len(t):
            return False
        dic = defaultdict(int)
        for i,j in zip(s,t):
            dic[i]+=1
            dic[j]-=1
        for i in dic:
            if dic[i] != 0:
                return False
        return True

你可能感兴趣的:(算法,哈希表,python,leetcode,算法)