-
Notifications
You must be signed in to change notification settings - Fork 77
/
valid_anagram.py
52 lines (38 loc) · 1.18 KB
/
valid_anagram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# coding: utf-8
"""
https://leetcode.com/problems/valid-anagram/
https://algodaily.com/challenges/is-an-anagram
"""
from collections import Counter
from collections import defaultdict
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
char_counts = defaultdict(int)
for char in s:
char_counts[char] += 1
for char in t:
char_counts[char] -= 1
for value in char_counts.values():
if value != 0:
return False
return True
class Solution2:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
char_counts = defaultdict(int)
for s_char, t_char in zip(s, t):
char_counts[s_char] += 1
char_counts[t_char] -= 1
for value in char_counts.values():
if value != 0:
return False
return True
class Solution3:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
class Solution4:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s.lower()) == Counter(t.lower())