In a preliminary interview, I came across this question:
If a line consists of words separated by a single space, print the words in descending order, sorted by the number of times they appear in the line.
For example, the input line "abb" generates the following output:
b : 2 a : 1
First, I would say that it is not so clear that the input line consists of single-letter words or letters with several letters. If so, it could be simple.
Here is my thought:
int c[26] = {0}; char *pIn = strIn; while (*pIn != 0 && *pIn != ' ') { ++c[*pIn]; ++pIn; }
I can get the frequency statistics of each one-letter word in the input string, and I can sort it (using QuickSort or something else). But after the count array is sorted, how do I get the one-letter word associated with the counter so that I can print them later in pairs?
If the input string consists of a multi-letter word, I plan to use map<const char *, int> to track the frequency. But then again, how to sort a key-value pair of a card?
The question is in C or C ++, and any suggestion is welcome.
Thanks!
source share