Java interview ,统计一篇英文文章的单词数,并输出次数最多的10个
先用一个List把文档中所有word存储起来;
然后用Map<String,Integer>来存储word和次数,Map中的key是不允许重复的;
然后把Map放到一个新的List中,对这个新的List进行按照其下的Map中的value值进行排序;
最后遍历上一步的List,输出打印top10。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordCounts {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<String,Integer>();
List<String> words = new ArrayList<String>();
List<Map.Entry<String, Integer>> list = null;
String fileName = "wordcounts2.txt";
FileReader file = new FileReader(fileName);
BufferedReader br = new BufferedReader(file);
String str = null;
while((str = br.readLine()) != null){
String strs[] = str.trim().split("[\\s+|,|.|!|?|:|;|“|”|’|-|]");
System.out.println("strs.length--------------" + strs.length);
for(int i=0;i<strs.length;i++){
// if(strs[i].trim().toString() != null){
if(strs[i].trim().toString() != ""){
words.add(strs[i]);
}
}
}
int count = 1;
for(String word:words){
if(map.containsKey(word)){
count = Integer.valueOf(map.get(word)) + 1;
}
map.put(word, count);
count = 1;
}
list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
//notice!! here,the following method will be sorted the list, rather than the map!!
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2){
if(o2.getValue()!=0&&o1.getValue()!=0&&o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else{
return -1;
}
}
});
//So,we should print the list,rather than the map
/*
int i = 0;
for(Map.Entry<String, Integer> word:map.entrySet()){
System.out.println("word:" + word.getKey() + "----------value:" + word.getValue());
if(i>8) break;
i++;
}*/
int i = 0;
for(Map.Entry<String, Integer> top10_words:list){
if(i == 10) break;
System.out.println("word:" + i + "-----" + top10_words.getKey() + "------counts:" + top10_words.getValue());
i++;
}
}
}
当然,作为一个developer,不能仅仅以实现功能为目的,而是怎么样以最高效率的实现,此时就需要不断的迭代,不断地降低时间复杂度。
开始的思路并没有想到用一个List把所有单词存储起来,而是直接在while循环中判断,这个时候就需要把map.containsKey()也放在while下的for循环中,
这样虽然没有开辟更多的内存空间,但是大大增加了时间复杂度。
在公司附近吃过午饭回来,让Guo Sir给review了一下我的code,遂有以上思路,于是coding之。
如有更高效的方法,希望不吝赐教。