Skip to content

Valid Anagram

LeetCode

01 · Question

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example:

  • Input: s = "anagram", t = "nagaram"
  • Output: true

02 · Solution

Reference solution

1def isAnagram(s: str, t: str) -> bool:
2 if len(s) != len(t):
3 return False
4
5 count = {}
6
7 for c in s:
8 count[c] = count.get(c, 0) + 1
9
10 for c in t:
11 if c not in count:
12 return False
13 count[c] -= 1
14 if count[c] == 0:
15 del count[c]
16
17 return len(count) == 0