May 26, 2024
s
and t
are anagrams.s
to create t
.s = "anagram"
, t = "nagaram"
s = "rat"
, t = "car"
s
and t
to count the occurrences of each character.false
.get
method to avoid key errors with a default value of 0
.def is_anagram(s, t):
if len(s) != len(t):
return False
count_s, count_t = {}, {}
for i in range(len(s)):
count_s[s[i]] = count_s.get(s[i], 0) + 1
count_t[t[i]] = count_t.get(t[i], 0) + 1
for char in count_s:
if count_s[char] != count_t.get(char, 0):
return False
return True
from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
false
.def is_anagram(s, t):
return sorted(s) == sorted(t)