PAT B 1042. Statistics character C ++ / JAVA

Source title

Please write a program to identify the most frequent letters that appear in the text for a given period.

Input formats:

Enter a given length of string in a row does not exceed 1000. String of ASCII code table any visible characters and spaces composition containing at least one English letter, end with a carriage return (Enter not count).

Output formats:

The maximum output frequency of the letters appear and the number of occurrences in a row, separated by a space between them. If there side by side, the output alphabetically minimum that letter. Case insensitive statistics, the output of lower-case letters.

Sample input:

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

Sample output:

e 7

analysis:

A total of 26 letters, no case, with a length of 26 times the recording array each letter appears, and then find the maximum value for

have to be aware of is:

1. If there is a tie, then the output of the minimum letter alphabetically

2. C ++ getline read by a single line, a carriage return as a delimiter

 

C ++ implementation:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 int main()
 6 {    
 7     const int n = 26;
 8     string str;
 9     string P = "abcdefghijklmnopqrstuvwxyz";
10     int arr[n] = { 0 };
11     getline(cin, str);
12     
13     for (int i = 0; i < str.size(); ++i)
14     {
15         if ((str[i] >= 'A' && str[i] <= 'Z'))
16         {
17             arr[str[i] - 'A']++;
18         }
19         else if (str[i] >= 'a' && str[i] <= 'z')
20         {
21             arr[str[i] - 'a']++;
22         }
23     }
24 
25     int maxIndex = 0;
26     int max = arr[0];
27     for (int i = 1; i < n; ++i)
28     {
29         if (max < arr[i])
30         {
31             max = arr[i];
32             maxIndex = i;
33         }
34     }
35 
36     cout << P[maxIndex] << " " << max;
37     return 0;
38 }

 

 

Java implementation:

Guess you like

Origin www.cnblogs.com/47Pineapple/p/11701440.html