Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created March 27, 2016 21:41
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/d2ccf6532524d8751c73 to your computer and use it in GitHub Desktop.
Save jianminchen/d2ccf6532524d8751c73 to your computer and use it in GitHub Desktop.
Sherlock and Anagram -
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
class Solution
{
static byte alphabet_count = 26;
static byte a = (byte)'a';
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());
for (int i = 0; i < t; i++)
{
string text = Console.ReadLine();
Console.WriteLine(solve(text));
}
}
static long solve(string text)
{
long count = 0;
byte[] str = TextToBytes(text);
int n = str.Length;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n + 1; j++)
{
count += (anagrams(str, i, j) - 1);
}
}
return count / 2;
}
private static long anagrams(byte[] str, int start, int end)
{
byte[] fP = GetFreq(str, start, end);
byte[] fW = GetFreq(str, 0, end - start);
int n = str.Length;
int l = end - start;
long count = 0;
for (int i = l; i < n; i++)
{
if (equalFreq(fP, fW))
{
count++;
}
fW[str[i]]++;
fW[str[i - l]]--;
}
if (equalFreq(fP, fW))
{
count++;
}
return count;
}
private static byte[] GetFreq(byte[] str, int start, int end)
{
byte[] f = new byte[alphabet_count];
for (int i = start; i < end; i++)
{
f[str[i]]++;
}
return f;
}
private static bool equalFreq(byte[] str1, byte[] str2)
{
for (int i = 0; i < alphabet_count; i++)
{
if (str1[i] != str2[i])
{
return false;
}
}
return true;
}
private static byte[] TextToBytes(string text)
{
int i = 0;
byte[] chars = new byte[text.Length];
foreach (char c in text.ToCharArray())
{
chars[i++] = (byte)((byte)c - a);
}
return chars;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment