mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Improve checking anagrams in O(n) with dictionary (#4806)
This commit is contained in:
parent
13fdf21c9c
commit
9ac94c09eb
@ -1,6 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
wiki: https://en.wikipedia.org/wiki/Anagram
|
wiki: https://en.wikipedia.org/wiki/Anagram
|
||||||
"""
|
"""
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
|
||||||
def check_anagrams(first_str: str, second_str: str) -> bool:
|
def check_anagrams(first_str: str, second_str: str) -> bool:
|
||||||
@ -16,10 +17,30 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
|
|||||||
>>> check_anagrams('There', 'Their')
|
>>> check_anagrams('There', 'Their')
|
||||||
False
|
False
|
||||||
"""
|
"""
|
||||||
return (
|
first_str = first_str.lower().strip()
|
||||||
"".join(sorted(first_str.lower())).strip()
|
second_str = second_str.lower().strip()
|
||||||
== "".join(sorted(second_str.lower())).strip()
|
|
||||||
)
|
# Remove whitespace
|
||||||
|
first_str = first_str.replace(" ", "")
|
||||||
|
second_str = second_str.replace(" ", "")
|
||||||
|
|
||||||
|
# Strings of different lengths are not anagrams
|
||||||
|
if len(first_str) != len(second_str):
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Default values for count should be 0
|
||||||
|
count = defaultdict(int)
|
||||||
|
|
||||||
|
# For each character in input strings,
|
||||||
|
# increment count in the corresponding
|
||||||
|
for i in range(len(first_str)):
|
||||||
|
count[first_str[i]] += 1
|
||||||
|
count[second_str[i]] -= 1
|
||||||
|
|
||||||
|
for _count in count.values():
|
||||||
|
if _count != 0:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
Loading…
Reference in New Issue
Block a user