Hackerrank Strings Solution : Sherlock and Anagrams.py
Hackerrank Strings Solution : Sherlock and Anagrams.py
Problem Statement:
Problem Statement:
Input Format
First line contains , the number of testcases. Each testcase consists of string in one line.
First line contains , the number of testcases. Each testcase consists of string in one line.
Constraints
String contains only the lowercase letters of the English alphabet.
String contains only the lowercase letters of the English alphabet.
Output Format
For each testcase, print the required answer in one line.
For each testcase, print the required answer in one line.
Sample Input#00
2
abba
abcd
Sample Output#00
4
0
Sample Input#01
5
ifailuhkqq
hucpoltgty
ovarjsnrbf
pvmupwjjjf
iwwhrlkpek
Sample Output#01
3
2
2
6
3
Explanation
Sample00
Let's say denotes the substring .
Let's say denotes the substring .
testcase 1:
For S=
For S=
abba
, anagrammatic pairs are: , , and .
testcase 2:
No anagrammatic pairs.
No anagrammatic pairs.
Sample01
Left as an exercise to you.
Left as an exercise to you.
Language: Python
Solution:
import collections
n = input()
while(n>0):
n-=1
k = raw_input()
dictionary = collections.defaultdict(int)
lst = list(k)
length = len(k)
for i in range(0,length):
for j in range(1,length-i+1):
sam = lst[i:i+j]
sam = sorted(sam)
dictionary[''.join(sam)] += 1
ans = 0
for value in dictionary.values():
ans += (value*(value-1))/2
print ans
import collections
n = input()
while(n>0):
n-=1
k = raw_input()
dictionary = collections.defaultdict(int)
lst = list(k)
length = len(k)
for i in range(0,length):
for j in range(1,length-i+1):
sam = lst[i:i+j]
sam = sorted(sam)
dictionary[''.join(sam)] += 1
ans = 0
for value in dictionary.values():
ans += (value*(value-1))/2
print ans
Comments
Post a Comment