我想不出爲什麼你被要求寫在想象中的那麼的形式,但是從我的頭頂,我應該這樣做:
Initialise your two queues for counts and letters.
For each letter in the input:
Search for letter in letter-queue.
If found
set count to the corresponding value from the count-queue + 1
remove from both queues
Else
set count to 1
Add the letter and count into both queues in the correct place
當你完成後,你有一個正確的順序來建立你的樹的隊列。
感覺就像一個隊列的濫用給我,但如果這就是你被要求做...
編輯什麼:這裏是如何我可能實際上寫它,沒有排隊等
unsigned char input[]="abracadabra";
int counts[256];
memset(counts, 0, 256 * sizeof(int));
unsigned char i;
unsigned char *pt = input;
int max = 0;
while(i = *pt++)
{
counts[i]++;
if(counts[i] > max) max = counts[i];
}
while(max)
{
int nmax = 0;
for(int c = 0 ; c < 256 ; c++)
{
if(counts[c] < max && counts[c] > nmax) nmax = counts[c];
if(counts[c] == max)
{
printf("%c: %d\n", c, max);
}
}
max = nmax;
}
你會用什麼來代替隊列? –
我只是使用一個簡單的固定大小的數組來存儲每個字符的計數,而不會搞亂容器。然後,我只是從最大的數到最小的數組迭代該數組(您可以記錄最大數小於當前計數,然後您只是迭代不同計數的次數。自由)。 – JasonD