作者 郑如滨
单位 集美大学
现在需要统计若干段文字(英文)中的单词数量,并且还需统计每个单词出现的次数。
注1:单词之间以空格(1个或多个空格)为间隔。
注2:忽略空行或者空格行。
基本版:
统计时,区分字母大小写,且不删除指定标点符号。
进阶版:
- 统计前,需要从文字中删除指定标点符号
!.,:*?
。 注意:所谓的删除,就是用1个空格替换掉相应字符。 - 统计单词时需要忽略单词的大小写。
输入说明
若干行英文,最后以!!!!!
为结束。
输出说明
单词数量
出现次数排名前10的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。
输入样例1
failure is probably the fortification in your pole
it is like a peek your wallet as the thief when you
are thinking how to spend several hard-won lepta
when you are wondering whether new money it has laid
background because of you then at the heart of the
most lax alert and most low awareness and left it
godsend failed
!!!!!
输出样例1
46
the=4
it=3
you=3
and=2
are=2
is=2
most=2
of=2
when=2
your=2
输入样例2
Failure is probably The fortification in your pole!
It is like a peek your wallet as the thief when You
are thinking how to. spend several hard-won lepta.
when yoU are? wondering whether new money it has laid
background Because of: yOu?, then at the heart of the
Tom say: Who is the best? No one dare to say yes.
most lax alert and! most low awareness and* left it
godsend failed
!!!!!
输出样例2
54
the=5
is=3
it=3
you=3
and=2
are=2
most=2
of=2
say=2
to=2
代码长度限制
16 KB
时间限制
1600 ms
内存限制
180 MB
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<String, Integer> array = new HashMap<>();
String[] a = new String[100000];//由于我是一开始给出的数组大小,题目中有一个限制条
//件,就是运行时间要长,如果太小运行速度太快,答案
//会无法通过(就很无语)😂
int count = 0;
while (true) {
String s = sc.next();
String s1 = s.toLowerCase();//这里是将所有大写的字母变成小写
String s2 = s1.replaceAll("[!.,:*?]","");//这里用的是用replaceAll来清除题目所要
//求的标点符号
if (s.equals("!!!!!")) {
break;
} else {
array.put(s2, 0);
a[count] = s2;
}
count++;
}
System.out.println(array.size());
//这里是实现统计文字中的单词数量
for (int i = 0; i < count; i++) {
if (!array.containsKey(a[i])){
array.put(a[i],1);
}else {
int k = array.get(a[i])+1;
array.put(a[i],k);
}
}
//这里是实现内容按序排列并且输出
List<Map.Entry<String, Integer>> freList = new ArrayList<>(array.entrySet());
freList.sort(new WordComparator());
int num = 0;
for (Map.Entry<String, Integer> e : freList) {
System.out.println(e.getKey() + "=" + e.getValue());
if(++num == 10) {
break;
}
}
}
}
//这里按照题目的要求,先比较次数,再比较键值字母的先后顺序
class WordComparator implements Comparator<Map.Entry<String, Integer>> {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue().equals(o2.getValue())) {
return o1.getKey().compareTo(o2.getKey());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
}
这一道题目可谓是非常麻烦,我也是看了别人的做法,自己改进了之后变得稍微简单一点,比较好理解一点,适合新手来看,如果是大佬的话,还是建议用别的方法,毕竟博主水平有限,只能做出这种代码啦🤣
欢迎大家来评论优化我这个代码嘻嘻😉