一.问题描述
Given two strings s and t , 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