您的位置:首页 > 编程语言

2015年去哪网校园招聘笔试题

2014-09-13 17:49 363 查看
编程题第三题,现场答题时没有api,手忙脚乱深受打击,回来之后发现笔试果然没有过,只能当作一次失败教训。

写一段代码,尝试在以下文本中搜索并打印出包含单词“your”(不区分大小写)的句子,并按照出现次数从高到底排序。

Make yourself at home.

None of your business.

I will be more careful.

How about going to a movie?

Your life is your own affair.

......

以下是个人思路,欢迎各位大牛指点纠正。



import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class test1 {
public static void main(String[] args) throws Exception{
List> mappingList= null;
Map map=new TreeMap(
/* 根据key按照降序排序(这里需要根据value降序排序)
* new Comparator(){
public int compare(String obj1,String obj2){
//降序排序
return obj2.compareTo(obj1);
}}*/
);

String path = "D://qunar.txt";
String aimWord = "your";
FileInputStream in = new FileInputStream(path);
BufferedReader dr = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = dr.readLine()) != null) {
int count = 0;
//用正则表达式去除句子中的标点符号
String str1 = str.replaceAll("[\\p{Punct}]", "");
String[] temp = str1.split(" ");
for (String t : temp) {
if(aimWord.equals(t.toLowerCase())){
count++;
}
}
if(count!=0){
map.put(str, count);
}
}

//通过ArrayList构造函数把map.entrySet()转换成list
mappingList =new ArrayList>(map.entrySet());
//通过比较器实现比较排序 (降序)
Collections.sort(mappingList,
new Comparator>() {
public int compare(Map.Entry mapping1,Map.Entry mapping2){
return mapping2.getValue().compareTo(mapping1.getValue());
}
}
);

for(Map.Entry mapping:mappingList){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
}
}


输出结果:
Your life is your own affair.:2

None of your business.:1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息