Skip to content

Instantly share code, notes, and snippets.

@suicide
Created February 3, 2013 19:07
Show Gist options
  • Save suicide/4703196 to your computer and use it in GitHub Desktop.
Save suicide/4703196 to your computer and use it in GitHub Desktop.
Facebook Hacker Cup 2013 Qualification Round Beautiful Strings Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* @author psy
*
*/
public class BeautifulStrings {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<String> output = new LinkedList<String>();
BeautyCounter beautyCounter = new BeautyCounter();
int strings = Integer.parseInt(in.nextLine());
for (int i = 1; i <= strings; i++) {
String string = in.nextLine();
int result = beautyCounter.count(string);
output.add("Case #" + i + ": " + result);
}
for (String out : output) {
System.out.println(out);
}
}
private static class BeautyCounter {
private CharComparator comparator = new CharComparator();
public int count(String string) {
// to lower
String preppedString = string.toLowerCase(Locale.US);
Map<Character, Integer> chars = new HashMap<Character, Integer>();
// filter characters
for (int i = 0; i < preppedString.length(); i++) {
Character character = preppedString.charAt(i);
if (Character.isLetter(character)) {
if (!chars.containsKey(character)) {
chars.put(character, 0);
}
chars.put(character, chars.get(character) + 1);
}
}
return doCount(chars);
}
private int doCount(Map<Character, Integer> chars) {
if (chars.size() > 26) {
throw new IllegalArgumentException("more than 26 characters given");
}
List<Entry<Character, Integer>> sortedChars = new ArrayList<Entry<Character, Integer>>(chars.entrySet());
Collections.sort(sortedChars, comparator);
int sum = 0;
int beautyIndex = 26;
for (Entry<Character, Integer> entry : sortedChars) {
sum += beautyIndex * entry.getValue();
beautyIndex--;
}
return sum;
}
private static class CharComparator implements Comparator<Map.Entry<Character, Integer>> {
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment