Given two strings s and t , write a function to determine if t is an anagram of s.
给定两个字符串 s 和 t ,写一个方程来确定 t 是否是 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?
如果输入字符串包含unicode字符怎么办?你将如何使你的解决方案面对这种情况?
Solution:
Python
(1)
def isAnagram(self,s,t):
#sorted()后,返回的是一个按字母顺序排序的list
return sorted(s) == sorted(t)
(2)
def isAnagram(self,s,t):
'''
get()方法语法:
dict.get(key, default=None)
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。
'''
dict1 = {}
dict2 = {}
for item in s:
dict1[item] = dict1.get(item,0) + 1
for item in t:
dict2[item] = dict2.get(item,0) + 1
return dict1 == dict2
原链接:
https://leetcode.com/problems/valid-anagram/description/