#输出频率最高且最先出现的字符#

假设有一个字符串,字符串内部的所有字符都是在ascii编码的范围内,编码求出字符串中出现频率最高的字符,如果频率最高的字符有几个字符出现的频率一样,则输出最先出现的字符。

 

如输入串为 “hello world, every body!”,则输出频率最高且最先出现的字符。

方法定义:char getMaxOccurChar(String str)

输入:hello world, every body!

输出:e

输入:aaaahfdfbbbbbbbbbb

输出:b

 

算法爱好者  贴出的思路

public class Main {

    public static void main(String[] args) {
        char result = getMaxOccurChar("hello world, every body!");
        // e
        System.out.println(result);
        result = getMaxOccurChar("aaaahfdfbbbbbbbbbb");
        // b
        System.out.println(result);
    }

    public static char getMaxOccurChar(String str) {

        int maxCount = 1;
        Character result = new Character(str.charAt(0));

        Map<Character, Integer> map = new LinkedHashMap<>();
        for (int i = 0; i < str.length(); i++) {
            Character content = str.charAt(i);
            Integer count = map.get(content);
            if (count == null) {
                map.put(content, 1);
            } else {
                map.put(content, count + 1);
            }
        }

        for (Map.Entry<Character, Integer> entry: map.entrySet()) {
            if (entry.getValue() > maxCount) {
                result = entry.getKey();
                maxCount = entry.getValue();
            }
        }
        return result;
    }
}

 

我想到另一种只需一次遍历的思路

private static char getMaxOccurChar(String str) {
    char[] chars = str.toCharArray();
    int minIndex = 0;
    int maxCount = 0;
   for(int x = 0; x < chars.length; x++){
     Pattern compile = Pattern.compile(String.valueOf(chars[x]));
     Matcher matcher = compile.matcher(str);
     int count = 0;
     while(matcher.find()){
       count++;
     }
     //数量大于
     if(count >  maxCount){
       maxCount = count;
       minIndex = x;
     }
     //数量一致
     else if(count == maxCount && minIndex > x){
       minIndex = x;
     }
   }
    return chars[minIndex];
  }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章