leetcode -字符串中字符出現頻率

題目:

有一篇英文文檔,由26個英文小寫字母、半⻆空格、英文逗號(,)、英文句號(.)29個字符組成,請給出出現頻次第N高的英文字符(簡單起⻅,每個字符出現的頻次兩兩不等)

  • 示例:輸入“abcdbcdcdd”,N=2時,返回結果爲c;N=3時,返回結果爲b
  • 函數入參:doc(string、char *,char[]等類型均可):文檔的全部字符串N(int類型):出現頻次第N高
  • 函數返回值:char類型:結果字符
    結題:
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.*;

class exception_handling {
    public static void main(String args[]) {
        System.out.println("In main " + doc("aaabbc", 'c', 3));
    }


    public static char doc(String str, char c, int n) {
        Map<Character, Integer> count = new HashMap<Character, Integer>();
        String[] myStrs = str.split("");
        //1、將字符串拆分放到map<字符,個數>
        for (int i = 0; i < myStrs.length; i++) {
            int num = 1;
            String currentStr = myStrs[i];
            if (count.containsKey(currentStr.charAt(0))) {
                num = count.get(currentStr.charAt(0)) + 1;
            }
            count.put(currentStr.charAt(0), num);
        }
        //2、將map放到list
        List<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(count.entrySet());
        //3、將list按map中value值倒敘排序
        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {

            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {

                return o1.getValue() > o2.getValue() ? -1 : 1;
            }
        });
        //4、list從0開始,所以取n-1的key
        return list.get(n - 1).getKey();

    }

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