#輸出頻率最高且最先出現的字符#

假設有一個字符串,字符串內部的所有字符都是在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];
  }

 

 

 

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