We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def sherlockAndAnagrams(s):
# abba ->
# a, a
# b, b
# ab, ba
# abb, bba
# NOTE: We ignore the full text (abba)
# cdcd ->
# c, c
# cd, dc
# dc, cd
# cdc, cdc
# d, d
# We want to go over every combination of the string
sorted_occurences = defaultdict(int)
count = 0
for i in range(0, len(s)):
for j in range(1, len(s) - i + 1):
substr = s[i : i + j]
sorted_substr = "".join(sorted(substr))
count += sorted_occurences[sorted_substr]
sorted_occurences[sorted_substr] += 1
return count
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
def sherlockAndAnagrams(s): # abba -> # a, a # b, b # ab, ba # abb, bba # NOTE: We ignore the full text (abba)