LeetCode242:Valid Anagram

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?


LeetCode:链接

直观的思路是,统计两个字符串中不同字符出现的次数,只有当两者出现的字符相同且出现的次数相同,那么它们是“anagram”。另外,两个长度不同的字符串一定不满足要求,可以辅助判断。 

通用的方法应该用字典处理,对于unicode也可以处理。分别对s和t生成两个字典,判断字典是否相同即可。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        def count(s):
            dict = {}
            for i in range(len(s)):
                if s[i] not in dict:
                    dict[s[i]] = 1
                else:
                    dict[s[i]] += 1
            return dict

        dict_s = count(s)
        dict_t = count(t)
        return dict_s == dict_t

更简单的写法,Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        alpha = {}
        beta = {}
        for c in s:
            alpha[c] = alpha.get(c, 0) + 1
        for c in t:
            beta[c] = beta.get(c, 0) + 1
        return alpha == beta

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值