Skip to content

Instantly share code, notes, and snippets.

@zackbloom
Created November 25, 2013 19:46
Show Gist options
  • Select an option

  • Save zackbloom/7647576 to your computer and use it in GitHub Desktop.

Select an option

Save zackbloom/7647576 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
class MyClass {
public void compute_palindromes(string[] words) {
// Write your code here
// To print results to the standard output you can use Console.WriteLine()
// Example: Console.WriteLine("Hello world!");
foreach(string word in words) {
Dictionary<char, int> dict = createWordDict(word);
if(canMakePaly(dict, word)) {
Console.WriteLine(makePaly(dict));
}
else {
Console.WriteLine(-1);
}
}
}
// this method can probably be optimized by calculating middle position of string builder
private string makePaly(Dictionary<char, int> dict) {
StringBuilder builder = new StringBuilder();
// find middle character if one exists
// and add it
foreach(KeyValuePair<char, int> kv in dict) {
int count1 = kv.Value;
if(kv.Value %2 == 1) {
while(count1 > 0) {
builder.Append(kv.Key);
count1--;
}
dict[kv.Key] = 0;
break;
}
}
foreach(KeyValuePair<char, int> kv in dict) {
int count = kv.Value;
//when alt = false add to beginning, when true add to end
bool alternate = false;
while(count > 0) {
if(alternate) {
builder.Insert(0, kv.Key);
}
else {
builder.Append(kv.Key);
}
alternate = !alternate;
count--;
}
}
return builder.ToString();
}
private bool canMakePaly(Dictionary<char, int> dict, string word) {
//if even char count
//if any odd numbers is false
bool ret = true;
int threshold = word.Length % 2;
int count = 0;
foreach(KeyValuePair<char, int> k in dict) {
if(k.Value %2 == 1) {
count++;
if(count > threshold) {
ret = false;
break;
}
}
}
return ret;
}
public Dictionary<char, int> createWordDict(string word){
Dictionary<char, int> dict = new Dictionary<char,int>();
foreach(char c in word) {
if(!dict.ContainsKey(c)) {
dict.Add(c, 0);
}
dict[c] = dict[c]+1;
}
return dict;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment