Java-查找最多字符出现的次数

//采用查表法进行查找

import java.util.HashMap;

public class CountMaxChar {

  public static void main(String[] args) {

    String str = "abbaaaaaa";
    HashMap<Character,Integer> hs = new HashMap<Character,Integer>();
    char[] chs = str.toCharArray();
    int maxCount = 0;
    char maxChar = 0;
    for(int i=0;i<chs.length;i++) {
      Integer tmp = hs.get(chs[i]);
      if(tmp == null) {
        tmp = hs.put(chs[i], 1);
      }else {
        tmp++;
        hs.put(chs[i],tmp);
        if(maxCount < tmp) {
          maxCount = tmp;
          maxChar = chs[i];
        }
      }
    }
    System.out.println("出现最多的是: "+maxChar);
    System.out.println("出现次数 : "+maxCount);
  }

}

posted @ 2019-01-04 21:06  文所未闻  阅读(1146)  评论(0编辑  收藏  举报