Advertisement
yangsec888

Sherlock and Anagrams 2

Feb 22nd, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. # https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps
  2. import os
  3. import sys
  4.  
  5. if __name__ == '__main__':
  6.     entries = int(input())
  7.     inputs = []
  8.     for _ in range(entries):
  9.         inputs.append(input().strip())
  10.     for my_string in inputs:
  11.         sub_strs={}
  12.         #build full substring in hash map: 'abba' => {'a': 2, 'ab': 2, 'abb': 2, 'aabb': 1, 'b': 2, 'bb': 1}
  13.         for x in range(len(my_string)):
  14.             for y in range(x,len(my_string)):
  15.                 str_l=list(my_string[x:y+1])
  16.                 str_l.sort()
  17.                 str="".join(str_l)
  18.                 sub_strs[str]=sub_strs.get(str,0)+1
  19.         #iterate through the hash map and count the anagrams one by one: C^2 => n*(n-1)/2
  20.         cnt=0
  21.         for n in sub_strs.values():
  22.             cnt += n*(n-1)//2
  23.         print(cnt)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement