题目:
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.
题意:
给定两个字符串s和t,写一个函数判断字符串t是否是由字符串s的字母颠倒顺序后得到的。
代码:
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t) :
return False
else :
dict1 = dict()
dict2 = dict()
for x in s : #初始化字典的每个key的value值为0
dict1[x] = 0
for x in t :
dict2[x] = 0
for x in s : #统计s中每个key出现的次数
dict1[x] = dict1[x] + 1
for x in t : #统计t中每个key出现的次数
dict2[x] = dict2[x] + 1
for x in dict1 :
if x not in dict2 : #如果s和t中key不一样,直接false
return False
else :
if dict1[x] != dict2[x] : #如果s和t中key一样,但出现次数不一样,直接false
return False
return True #否则,每个key一样,且出现次数一样,返回True