PAT 乙級 1042.字符統計 C++/Java

題目來源ios

請編寫程序,找出一段給定文字中出現最頻繁的那個英文字母。c++

輸入格式:

輸入在一行中給出一個長度不超過 1000 的字符串。字符串由 ASCII 碼錶中任意可見字符及空格組成,至少包含 1 個英文字母,以回車結束(回車不算在內)。數組

輸出格式:

在一行中輸出出現頻率最高的那個英文字母及其出現次數,其間以空格分隔。若是有並列,則輸出按字母序最小的那個字母。統計時不區分大小寫,輸出小寫字母。spa

輸入樣例:

 This is a simple TEST.  There ARE numbers and other symbols 1&2&3...........

輸出樣例:

 e 7

 

分析:

  • 空格也算是字符串的一部分(c++用getline接收空格)code

  • 只記錄字母,將全部字母轉換成小寫,出現次數存放在int數組blog

    • 數組下標:0對應a,1對應b,...,25對應zci

  • 在數組中找到最大值,輸出下標對應的字母,以及數組對應的值字符串

 

c++實現: 

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <cctype>
 5 using namespace std;
 6 
 7 int main() {
 8     string str;
 9     getline(cin, str);
10     // 0-a, 1-b, .... 25-z
11     vector<int> arr(26);
12 
13     for (int i = 0; i < str.size(); ++i) {
14         if (isalpha(str[i])) {
15             arr[tolower(str[i]) - 97]++;
16         }
17     }
18     int max = 0;
19     for (int i = 1; i < arr.size(); ++i) {
20         if (arr[i] > arr[max]) {
21             max = i;
22         }
23     }
24     cout << (char)('a' + max) << ' ' << arr[max] << endl;
25     return 0;
26 }

 

 

Java實現:

相關文章
相關標籤/搜索