编程面试题001——wordcount
2015-10-03 17:36
429 查看
编程面试题001——wordcount
**题目背景介绍:
**这一题是我在面试某互联网企业时遇到的一道编程算法题,算是比较简单的一题,纪录下来,总结面试中遇到的点点滴滴。
题目描述:
有一篇文章只包含英文单词,请按它们的出现次数排序,出现最多的先输出;如果出现次数相等的,按字符串ASCII排序升序输出。**
输入:
**第一行会是行数N( 0 < N <= 500)。
之后N行中的每行会是一个或多个英文单词。
数据总大小不超过100K。
**
输出:
**<单词1><空格><次数1>
<单词2><空格><次数2>
由于是在hihoCoder平台上面做的,对于各种语言的api没有什么限制。所以使用了java中的pattern 和 map来解决此题,既方便又快捷。
my code :
public class Main { public static void main(String[] args){ int rowCount = 0; Scanner sc = new Scanner(System.in); rowCount = sc.nextInt(); int i=0; StringBuilder sb = new StringBuilder(); while(i<=rowCount){ sb.append(sc.nextLine()+" "); i++; } //单词匹配 Pattern pattern= Pattern.compile("[a-zA-Z]+"); Matcher matcher=pattern.matcher(sb.toString()); Map<String,Integer> words=new HashMap<String,Integer>(); String word=""; int wordCount; while(matcher.find()){ word=matcher.group(); if(words.containsKey(word)){ wordCount=words.get(word); words.put(word, wordCount+1); }else{ words.put(word, 1); } } List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String,Integer>>(words.entrySet()); //对集合进行排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { if (o1.getValue() > o2.getValue()) { return -1; } else if (o1.getValue() == o2.getValue()) { return o1.getKey().compareTo(o2.getKey()); } else { return 1; } } }); //输出结果 StringBuilder output = new StringBuilder(); for(Map.Entry<String,Integer> bean : list){ output.append(bean.getKey()).append(" ").append(bean.getValue()).append("\n"); } System.out.println(output.toString()); } }