首页 > 代码库 > 找出给定字符串中出现最多的字符和次数

找出给定字符串中出现最多的字符和次数

public static void findMaxCountChar(String str) {
        if (str == null || str == "")
            return;
        Map<String, Integer> map = new HashMap<String, Integer>();
        int maxCount = 0;
        String maxCountStr = "";
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < str.length(); i++) {
            String key = String.valueOf(str.charAt(i));
            if (maxCount >= str.length() / 2) {
                if (maxCountStr == key) {
                    maxCount++;
                }
            } else {
                if (!map.containsKey(key)) {
                    map.put(key, 1);
                } else {
                    int count = map.get(key);
                    map.put(key, count + 1);
                    if ((count + 1) > maxCount) {
                        maxCount = count + 1;
                        maxCountStr = key;
                        list.clear();
                        list.add(key);
                    } else if ((count + 1) == maxCount) {
                        list.add(key);
                    }
                }
            }

        }
        System.out.println("最大次数" + maxCount);
        if (maxCount >= str.length() / 2) {
            System.out.println("字符" + maxCountStr);
        } else {
            System.out.println("字符" + list);
        }
    }

 

找出给定字符串中出现最多的字符和次数