LeetCode 字符串-有效的字母异位词

本博客探讨如何在LeetCode中判断两个字符串是否互为字母异位词,通过Python代码实现,包括将字符串转化为字符集进行比较的方法。

有效的字母异位词

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

示例 1:

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

示例 2:

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

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

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

Python:

我的代码1:

1.分别对两个字符串 转成

   def isAnagram(s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic_s = {}
        dic_t = {}
        
        for char in s:
            if char in dic_s:
                dic_s[char] += 1
            else:
                dic_s[char] = 1
        for char in t:
            if char in dic_t:
                dic_t[char] += 1
            else:
                dic_t[char] = 1

        return operator.eq(dic_t,dic_s)
代码2:

1.判断字符串长度
2.丢到 set 里面判断两个 set 之后长度
3.比较字符出现的个数

   def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        set_s = set(s)
        set_t = set(t)
        if len(set_s) != len(set_t):
            return False
        for char in set_s:
            if s.count(char) != t.count(char):
                return False
        return True

代码3:
字符转为 ASCII 值

 def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic_s = {}
        dic_t = {}
        if len(s) != len(t):
            return False
        for char in s:
            if ord(char) in dic_s:
                dic_s[ord(char)] += 1
            else:
                dic_s[ord(char)] = 1
        for char in t:
            if ord(char) in dic_t:
                dic_t[ord(char)] += 1
            else:
                dic_t[ord(char)] = 1

        return operator.eq(dic_t,dic_s)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值