Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created March 14, 2016 06:05
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/78346475b6a7ce5d1681 to your computer and use it in GitHub Desktop.
Save jianminchen/78346475b6a7ce5d1681 to your computer and use it in GitHub Desktop.
Anagram - using Dictionary, keyValuePair class
using System;
using System.Collections.Generic;
using System.IO;
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 = Int32.Parse(Console.ReadLine());
for (int i = 0; i < T; i++) {
string input = Console.ReadLine();
Console.WriteLine(solve(input));
}
}
private static int solve(string s) {
if (s.Length % 2 != 0)
return -1;
int length = s.Length / 2;
string a = s.Substring(0, length);
string b = s.Substring(length, length);
Dictionary<char,int> aChars = new Dictionary<char,int>();
Dictionary<char,int> bChars = new Dictionary<char,int>();
int different = 0;
for (int i = 0; i < length; i++) {
if (a[i] != b[length-1-i]) {
if (!aChars.ContainsKey(a[i]))
aChars.Add(a[i], 1);
else
aChars[a[i]]++;
if (!bChars.ContainsKey(b[length-1-i]))
bChars.Add(b[length-1-i], 1);
else
bChars[b[length-1-i]]++;
different++;
}
}
foreach (KeyValuePair<char,int> kvp in bChars) {
if (aChars.ContainsKey(kvp.Key)) {
different -= Math.Min(aChars[kvp.Key], kvp.Value);
}
}
return different;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment