Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return 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的翻譯就是 變位詞适肠;(變換或顛倒字母順序而成另一詞的)回文構(gòu)詞法
所以s和t的字母應(yīng)該是一致的捌袜,只是字母順序不一樣。直覺上可以判斷t中的每個元素是不是都在t里面,如果是墅垮,就返回true,否則就返回false。
考慮到元素一樣,順序不一致骡送。還可以對s,t進行排序絮记,以及使用系統(tǒng)自帶的collections.Counter()
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
import collections
return collections.Counter(s) == collections.Counter(t)
def isAnagram2(self, s, t):
return sorted(s) == sorted(t)
if __name__ == '__main__':
sol = Solution()
s = "anagram"
t = "nagaram"
print sol.isAnagram(s, t)
print sol.isAnagram2(s, t)