Reputation: 20895
For practice, I want to order an ASCII string in by frequency and then by alphabetical order in java, so 'banana' should become 'bnnaaa', and 'grammar' should become 'gaammrr'. Here's what I have so far.
public static orderByFrequencyAndThenAlphabet(String str) {
// 128 ASCII characters possible.
int[] charCount = new int[128]
// Get the counts.
str = str.toCharArray();
for (char c : str) {
charCount[int(c)] += 1;
}
// Sort by frequency...
}
As you see, I made a data structure store the counts for each character in the input string. However, how do I now use the data structure to sort the characters by frequency? Should I look into using a priority queue?
Upvotes: 1
Views: 858
Reputation: 3016
All you have to do is create an character array to store all characters in the string (Note the size of the character array must be the length of the string). Then you apply a sort to the character array(bubble sort of whatever you are comfortable with) then you construct a new string with the sorted character array (Note ensure proper character casing when sorting the array). This is inefficient but it gets the job done.
Upvotes: 1