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?
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