Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 9, 2017 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/53a292fc446944dded54de1b507a3809 to your computer and use it in GitHub Desktop.
Save jianminchen/53a292fc446944dded54de1b507a3809 to your computer and use it in GitHub Desktop.
Sherlock and anagram - code review 2
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
class Solution
{
/*
* January 8, 2016
* Julia reviews the code.
*/
static void Main(String[] args)
{
var queries = int.Parse(Console.ReadLine());
var frequencyTable = new Dictionary<char, int>();
var total = new Dictionary<int, int>(); // key - hashcode of ...
var stringBuilder = new StringBuilder();
while (queries-- > 0)
{
total.Clear();
// convert to 0, 1 ?
var str = Console.ReadLine();
// substring length
for (var i = 1; i < str.Length; i++)
{
for (var j = 0; j <= str.Length - i; j++)
{
frequencyTable.Clear();
for (var k = j; k < j + i; k++)
{
// get hashcode of substring
if (frequencyTable.ContainsKey(str[k]))
{
frequencyTable[str[k]]++;
}
else
{
frequencyTable.Add(str[k], 1);
}
}
// convert to hash code
stringBuilder.Clear();
foreach (var item in frequencyTable.OrderBy(s => s.Key))
{
stringBuilder.Append(item.Key + item.Value.ToString());
}
// ?
var key = stringBuilder.ToString().GetHashCode();
if (total.ContainsKey(key))
{
total[key]++;
}
else
{
total.Add(key, 1);
}
}
}
// get pairs
long result = 0;
foreach (var item in total)
{
result += item.Value * (item.Value - 1) / 2;
}
Console.WriteLine(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment