使用java,计算一段文本中出现英语单词次数最多的单词

package cn.rrl.interview;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;
/**
 * 计算一段文本中出现英语单词次数最多的单词
 * @author Mr.xiao
 *
 */
public class HelloCountWord {

    /**
     * @param args
     */
    public static void main(String[] args) {
       String str = "But you you by the end of the year,look to the skies above London and you'll see the usual suspects raninclouds,planes and pigeons.you might just see something else.";
       TreeSet re = ChangeTheWord(str);//把单词转换成   (次数:单词)  的格式 放入TreeSet中
       ArrayList results = getTheMax(re);//得到TreeSet中的最大值,以及一样大的值
       for(String result : results){ //
              System.out.println(result);
         }
   }
    /**
     * 得到TreeSet中的最大值,以及一样大的值
     * @param re
     * @return
     */
    public static ArrayList getTheMax(TreeSet re){
         ArrayList results = new ArrayList();
           results.add(re.first());//得到次数最多的单词
           re.remove(re.first());
           for(String s : re){//最大值如果和下一个单词的数量一致,再次添加
               if(s.split(":")[0].equals(results.get(0).split(":")[0])){
                   results.add(s);
               }else{
                   break;
               }
           }
        return results;
    }
    /**
     * 把单词转换成   (次数:单词)  的格式
     * @param str
     * @return
     */
    public static TreeSet ChangeTheWord(String str){
        String [] strs = str.split("[ '.,]");
        ArrayList list = new ArrayList();// 用于存放字符串数组
        TreeSet result = new TreeSet(new MyComparator());//TreeSet降序排列
        for(String s : strs){
            list.add(s);
        }
        for(String s : list){
            int count = Collections.frequency(list, s);//使用 Collections.frequency 找出重复的单词次数
            result.add(count+":"+s);
        }
        return result;
    }
}
/**
 * 实现降序排列
 * @author Mr.xiao
 *
 */
class MyComparator implements Comparator {
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
    
}

你可能感兴趣的:(java基础,面试题)