import java.io.File; import java.util.Scanner; import java.util.Arrays; public class BeautifulStrings { public static int totalBeauty(String line) { //build alphabet/freq/val triplets String[][] alphabet_freq = { {"a", "0"}, {"b", "0"}, {"c", "0"}, {"d", "0"}, {"e", "0"}, {"f", "0"}, {"g", "0"}, {"h", "0"}, {"i", "0"}, {"j", "0"}, {"k", "0"}, {"l", "0"}, {"m", "0"}, {"n", "0"}, {"o", "0"}, {"p", "0"}, {"q", "0"}, {"r", "0"}, {"s", "0"}, {"t", "0"}, {"u", "0"}, {"v", "0"}, {"w", "0"}, {"x", "0"}, {"y", "0"}, {"z", "0"} }; line = line.toLowerCase(); StringBuffer buff = new StringBuffer(line); final int BASE_ALPHA = 97; //97 - 122 (int) char for (int i = 0; i < buff.length(); i++) { char temp = buff.charAt(i); int tempnum = (int) temp; int setfreq = tempnum-BASE_ALPHA; if (tempnum >= 97 && tempnum <= 122) { for (int j = i; j < buff.length(); j++) { char tempother = buff.charAt(j); if (tempother == temp) { buff.replace(j,j+1," "); //add to freq array int tempArrayValue = Integer.parseInt(alphabet_freq[setfreq][1]); tempArrayValue += 1; alphabet_freq[setfreq][1] = Integer.toString(tempArrayValue); } } } else { continue; } } //initialize from 26-1 if whole alphabet is represented boolean end = false; int k = 0; int total = 0; int first = 26; int currentLargestPlace = 0; int currentLargestFreq = 0; while (end == false) { //debug //System.out.println(Arrays.toString(alphabet_freq[k])); int thisFreq = Integer.parseInt(alphabet_freq[k][1]); if (thisFreq > currentLargestFreq) { //System.out.println("First if block"); currentLargestFreq = thisFreq; currentLargestPlace = k; } //when reach end, first check if 0 if (k == 25) { //System.out.println("Second if block"); if (currentLargestFreq == 0) { //System.out.println("Embedded if block"); end = true; break; } total += currentLargestFreq * first; //System.out.println("Current total = " + total); first -= 1; currentLargestFreq = 0; alphabet_freq[currentLargestPlace][1] = "0"; k = 0; } else { k++; } } return total; } public static void main(String[] args) { try { File file = new File(args[0]); Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) { System.out.println(totalBeauty(scanner.nextLine())); } } catch (Exception e) { System.out.println(e); } } }