读入包含若干个单词的文本数据,将所有内容转换为大写,统计每个单词与该单词的出现次数。此外,还需要统计每个字符及其出现次数(不包括空格)。
输入格式:
若干行的单词,以空格作为分隔符,每行单词数量不定。
遇到一行数据“0000”,读取数据结束。(字符串“0000”不计入上述统计数据)
输出格式:
全部数据读取完成,输出如下信息:
(1)出现次数最多的单词及其出现次数;若次数相同,输出字典序最大的单词。
(2)出现次数最少的单词及其出现次数;若次数相同,输出字典序最小的单词。
(3)每个字母,按A到Z的顺序以及次数。
其中,单词和字母占10个字符位置,左对齐;计数(即:出现次数)占8位,右对齐。
提示:
Java语言,建议使用HashMap存储数据;
Python语言,建议使用dict存储数据。
输入样例:
I would rather have had one breath of her hair
one KISS of her mouth one touch of her hand than an eternity without it
I WOULD rathER haVE HAD oNe BreatH Of Her Hair
ONE kiss of her mouth one touch of her hand than an eternity WITHOUT IT
0000
输出样例:
ONE 6
AN 2
A 16
B 2
C 2
D 6
E 22
F 6
G 0
H 26
I 12
J 0
K 2
L 2
M 2
N 14
O 20
P 0
Q 0
R 16
S 4
T 20
U 8
V 2
W 4
X 0
Y 2
Z 0
解题思路:
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Map<String, Integer> map = new TreeMap<String, Integer>();
String str;
int[] book = new int[200];
while (true) {
str = input.nextLine();
if (str.equals("0000")) break;
str = str.toUpperCase();
for (int i = 0; i < str.length(); i++)
book[str.charAt(i)]++;
String[] temp = str.split(" ");
for (int i =0; i < temp.length; i++) {
if (map.containsKey(temp[i]))
map.put(temp[i],map.get(temp[i]) + 1);
else
map.put(temp[i], 1);
}
}
String text_Max = null, text_Min = null;
int Max = 0, Min = 100000000;
Iterator<Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> temp = it.next();
String key = temp.getKey();
int value = temp.getValue();
if (value >= Max) {
Max = value;
text_Max = key;
}
if (value < Min) {
Min = value;
text_Min = key;
}
}
System.out.printf("%-10s%8d\n", text_Max, Max);
System.out.printf("%-10s%8d\n", text_Min, Min);
for (int i = 'A'; i <= 'Z'; i++)
System.out.printf("%-10c%8d\n", i, book[i]);
input.close();
}
}