leetcode 242. Valid Anagram 解法 python

一.问题描述

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?

 

二.解题思路

两字符串anagram:即由相同字母并且该字母数量也相同组成。可以理解为不同排列。

1.首先判断两字符串长度是否相同,不相同的话一定不是anagram。

2.统计2个字符串中每个字符的出现次数,然后遍历比较字符是否出现在另一字符串并且次数相同。

时间复杂度:O(N)

可以通过collections的Counter计数也可以自己实现

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.Counter

from collections import Counter
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s)!=len(t):return False
        c1,c2=Counter(s),Counter(t)
        return c1==c2   
# python overload the == operator for dic comparison,so you do not need to compare the key and value by yourself

2.字典

def isAnagram(self, s, t):
        dic = {}
        for ch in s:
            dic[ch] = dic.get(ch, 0) + 1
        for ch in t:
            if ch not in dic:return False
            dic[ch] -= 1
            if dic[ch] == 0:del dic[ch]
        return len(dic) == 0

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值