Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sherlocks And Anagram - using Dictionary, construct key like this: ab, using {0}-1{1}-1
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int t = int.Parse(Console.ReadLine());
while(t-- > 0){
Dictionary<string,int> dict = new Dictionary<string,int>();
string s = Console.ReadLine().Trim();
for(int i = 0 ; i < s.Length;i++){
int[] count = new int[26];
for(int j = i ; j < s.Length ; j++){
int acode = (int)s[j] - (int)'a';
count[acode]++;
string key = GiveKey(count);
//Console.WriteLine
if(!dict.ContainsKey(key))
dict.Add(key,0);
dict[key]++;
}
}
long total = 0 ;
foreach(var item in dict){
if(item.Value > 1){
//Console.WriteLine(item.Value + " " + item.Key);
total = total + (item.Value * (item.Value - 1)) / 2;
//total = total - 1;
}
}
Console.WriteLine(total);
}
}
static string GiveKey(int[] arr){
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < 26 ; i++){
sb.AppendFormat("{0}-",arr[i]);
}
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment