PAT 乙级 1042.字符统计 C++/Java

题目来源

请编写程序,找出一段给定文字中出现最频繁的那个英文字母。

输入格式:

输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。

输出格式:

在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。

输入样例:

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

输出样例:

 e 7

 

分析:

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

  • 只记录字母,将所有字母转换成小写,出现次数存放在int数组

    • 数组下标:0对应a,1对应b,...,25对应z

  • 在数组中找到最大值,输出下标对应的字母,以及数组对应的值

 

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实现:

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 
 5 public class Main {
 6     public static void main(String[] args) throws IOException {
 7         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
 8         String s = in.readLine().replaceAll("[^a-zA-Z]", "").toLowerCase();
 9         int[] arr = new int[26];
10         int max = 0;
11         for (int i = 0; i < s.length(); i++) {
12             arr[s.charAt(i) - 'a']++;
13         }
14         for (int i = 1; i < 26; i++) {
15             if (arr[i] > arr[max]) {
16                 max = i;
17             }
18         }
19         System.out.println((char) (max + 'a') + " " + arr[max]);
20     }
21 }

 

 

 

posted @ 2019-10-18 23:55  47的菠萝~  阅读(119)  评论(0编辑  收藏  举报