java编程 一个字符串中出现次数最多的字符以及次数

思路:采用替换法,把字符串中的每个字符以此替换为空,然后比较前后串的长度,找出长度差最大的一个或多个。
package lpp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class CountChar {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String aa = "zuitla我我love我朝tt";
       
        HashMap<String, Integer> result = mostEle(aa);
        ArrayList<Integer> c = new ArrayList<Integer>(result.values());
        Set<String> s = result.keySet();
        System.out.print("一共有" + result.size() + "元素最多。它们分别是");
        System.out.print(s);
        System.out.println(",分别出现了" + c.get(0) + "次。");    
    }
   
    private static HashMap<String, Integer> map;

    public static HashMap<String, Integer> mostEle(String strArray) {
      map = new HashMap<String, Integer>();
      int count = 0;
      int result = 0;
      for (int i = 0; i < strArray.length(); i++) {
       String temp = strArray.replaceAll(strArray.charAt(i)+"", "");
       count = (strArray.length() - temp.length());
       if (count > result) {
        map.clear();
        map.put(strArray.charAt(i)+"", count);
        result = count;
       } else if (count == result)
        map.put(strArray.charAt(i)+"", count);
      }
      return map;
     }
}

你可能感兴趣的:(java)