LeetCode 242. Valid Anagram
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dic = dict()
for elm in s:
if elm not in dic:
dic[elm] = 1
else:
dic[elm] += 1
for elm in t:
if elm not in dic:
return False
else:
dic[elm] -= 1
if dic[elm] < 0:
return False
return True
dicのkeyは出てきた文字、valueはそれが何回出てきたか
文字列sに出てくる文字とその出現回数をdicに保存して、
文字列tに出てきた文字がdicの中になければFalseを返し、dicの中にあればvalueを1減らす。
valueがマイナスになれば、その文字がsに出てくる回数よりもtに出てくる回数の方が多いことになるのでFalseを返す。
最後までfor文が回ればアナグラム