File tree 1 file changed +25
-4
lines changed
1 file changed +25
-4
lines changed Original file line number Diff line number Diff line change 1
1
"""
2
2
wiki: https://en.wikipedia.org/wiki/Anagram
3
3
"""
4
+ from collections import defaultdict
4
5
5
6
6
7
def check_anagrams (first_str : str , second_str : str ) -> bool :
@@ -16,10 +17,30 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
16
17
>>> check_anagrams('There', 'Their')
17
18
False
18
19
"""
19
- return (
20
- "" .join (sorted (first_str .lower ())).strip ()
21
- == "" .join (sorted (second_str .lower ())).strip ()
22
- )
20
+ first_str = first_str .lower ().strip ()
21
+ second_str = second_str .lower ().strip ()
22
+
23
+ # Remove whitespace
24
+ first_str = first_str .replace (" " , "" )
25
+ second_str = second_str .replace (" " , "" )
26
+
27
+ # Strings of different lengths are not anagrams
28
+ if len (first_str ) != len (second_str ):
29
+ return False
30
+
31
+ # Default values for count should be 0
32
+ count = defaultdict (int )
33
+
34
+ # For each character in input strings,
35
+ # increment count in the corresponding
36
+ for i in range (len (first_str )):
37
+ count [first_str [i ]] += 1
38
+ count [second_str [i ]] -= 1
39
+
40
+ for _count in count .values ():
41
+ if _count != 0 :
42
+ return False
43
+ return True
23
44
24
45
25
46
if __name__ == "__main__" :
You can’t perform that action at this time.
0 commit comments