Problem statement:
Difficulty: Moderate
More C# solution:
Solution 1:
Julia, here is code you should study; more advanced than yours.
a person works for Box Inc.
https://www.hackerrank.com/__run
https://gist.github.com/jianminchen/576ecf2cd127a703cb7a
Learn C# coding: readonly, Equals, override, constructor, use byte instead of int. Take some time off, learn C#, OO design basics:
Here are the code, make some comments to read some articles to catch up:
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);
}
/*
Design concern:
hashcode for anagram strings - same
use unchecked function
figure out this design:
a b c ... y z
3 1 1 1
3*(26*13)^25 1*(26*13)^24 1*(26*13) 1
*/
public override int GetHashCode()
{
int hc = Array.Length;
for (int i = 0; i < Array.Length; ++i)
{
hc = unchecked(hc * 13 + Array[i]); // Julia, figure out how this hashcode is working for anagram
}
return hc;
}
public readonly byte[] Array; // Julia, readonly, why to use byte[]
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) // override Equals function
{
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]); // byte.CompareTo
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)));
}
}
}
No comments:
Post a Comment