找出某个String中出现次数最多的字符,并输出次数(字符较长)

利用HashMap。
K 对应每一个字符;V对应相应的出现次数。

可用此思想解决 大数据情况下对 榜单音乐、搜索次数最多的词、等等的排序

代码如下

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 功恒 on 2016/9/26 0026.
 */
public class Mostchar {
    public static void main(String[] args){
        String str = "aaabbBBBBcc";
        char[] chars = str.toCharArray();
        Map<Character,Integer> map=mapFun(chars);//存放好之后的map
        int max=0;
        for (int i=0;i<str.length();i++){
            if (max<map.get(chars[i])){
                max=map.get(chars[i]);
            }
        }
        System.out.print("max = "+max);
    }

    public static Map<Character,Integer>  mapFun (char[] chars){
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        if (chars != null&& chars.length!=0){
            for (int i=0;i<chars.length;i++){
                if (null!=map.get(chars[i])){
                     map.put(chars[i],map.get(chars[i])+1);
                }else {
                    map.put(chars[i],1);
                }
            }
        }
        return map;
    }

}
posted on 2016-09-26 23:53  gerhold123  阅读(130)  评论(0编辑  收藏  举报