Skip to content

Instantly share code, notes, and snippets.



Created Aug 19, 2020
What would you like to do?
Anagram substring quantity
from collections import defaultdict
def count_anagram(str):
subs = defaultdict(int)
for i in range(len(str)):
for j in range(1, len(str) + 1):
if j > i:
subs[''.join(sorted(str[i:j]))] += 1
count = 0
for k, qty in subs.items():
if qty > 1:
count += int(qty * (qty - 1) / 2)
return count
if __name__ == "__main__":
print([count_anagram(x) for x in ['abba', 'banana']])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment