Created
November 11, 2013 08:16
-
-
Save jeremy5189/7409642 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Occurrence Count | |
* http://oj.sslab.cs.nthu.edu.tw/problems/21 | |
* Authored by Jeremy Yen 2013.11.11 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <ctype.h> // 轉大寫 | |
#define N 100 | |
// 快速排序法的比對函數 | |
int compare (const void * a, const void * b); | |
int main() | |
{ | |
int count[26], origin[26], i, j; | |
char str[N]; | |
// 讀入 | |
while(fgets(str, N, stdin)) | |
{ | |
// 初始化計數陣列 | |
for( i = 0; i < 26; i++ ) | |
count[i] = 0; | |
i = 0; | |
while( str[i] != '\0' ) | |
{ | |
// 每個字先轉大寫,再轉 ASCII 的數字, | |
// 再減 65 變成 0 到 25,當成陣列的索引 | |
int index = (int)toupper(str[i]) - 65; | |
if( index != -33 ) // 略過空格 | |
count[index]++; | |
i++; | |
} | |
// 複製一份陣列(排序時陣列索引會亂掉,索引用以表示字母) | |
for( i = 0; i < 26; i++ ) | |
origin[i] = count[i]; | |
// stdlib 裡的快速排序法 | |
qsort(count, 26, sizeof(int), compare); | |
// 準備輸出結果 | |
for( i = 0; i < 26; i++ ) | |
{ | |
if( count[i] != 0 ) | |
{ | |
int key; | |
// 照字母順序回去查對應表 | |
for( j = 0; j < 26; j++ ) | |
{ | |
// 找到數量一樣的 | |
if( origin[j] == count[i] ) | |
{ | |
key = j; // 紀錄 | |
origin[j] = 0; // 下次會跳過 | |
break; | |
} | |
} | |
// 印出索引(轉回char) | |
printf("%c %d\n", (char)(key + 65), count[i] ); | |
} // End if | |
} // End for i | |
} // End While | |
return 0; | |
} | |
int compare (const void * a, const void * b) | |
{ | |
// b - a 反向排序 | |
return ( *(int*)b - *(int*)a ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment