Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created March 27, 2016 21:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/576ecf2cd127a703cb7a to your computer and use it in GitHub Desktop.
Save jianminchen/576ecf2cd127a703cb7a to your computer and use it in GitHub Desktop.
Sherlock And Anagram - C# define a new class with all functions - hashcode
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SherlockAndAnagrams
{
class CharCount
{
protected bool Equals(CharCount other)
{
return Equals(Array, other.Array);
}
public override int GetHashCode()
{
int hc = Array.Length;
for (int i = 0; i < Array.Length; ++i)
{
hc = unchecked(hc * 13 + Array[i]);
}
return hc;
}
public readonly byte[] Array;
public CharCount()
{
Array = new byte[26];
}
public CharCount(CharCount charCount)
{
Array = new byte[26];
for (int i = 0; i < 26; i++)
{
Array[i] = charCount.Array[i];
}
}
public void AddChar(char ch)
{
Array[ch - 'a']++;
}
public override bool Equals(object obj)
{
CharCount other = obj as CharCount;
if (obj == null)
{
return false;
}
for (int i = 0; i < 26; i++)
{
int val = Array[i].CompareTo(other.Array[i]);
if (val != 0)
{
return false;
}
}
return true;
}
}
class Program
{
static void Main(string[] args)
{
int t = int.Parse(Console.ReadLine());
for (int i = 0; i < t; i++)
{
HandleTestCase();
}
}
private static void HandleTestCase()
{
IDictionary<CharCount, int> dictionary = new Dictionary<CharCount, int>();
string str = Console.ReadLine();
for (int i = 0; i < str.Length; i++)
{
CharCount charCount = new CharCount();
for (int j = i; j < str.Length; j++)
{
charCount.AddChar(str[j]);
if (!dictionary.ContainsKey(charCount))
{
dictionary.Add(new CharCount(charCount), 1);
}
else
{
dictionary[charCount] = dictionary[charCount] + 1;
}
}
}
Console.WriteLine(dictionary.Values.Sum(value => ((value * (value - 1)) / 2)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment