编程题:统计字符串中出现次数最多的字母

题目如下:1个字符串中可能包含a-z中的多个字符,字符也可能重复,例如:String data = “aabcexmkduyruieiopxzkkkkasdfjxjdsds”;写一个程序,对于给定一个这样的字符串求出字符串出现次数最多的那个

话不多说,上代码:

用collections.sort()来解决

       	String str = "sdnasjhdasdaksnfcjdshdfudfhaosinfdaaasjncxkjz";
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        char[] arr = str.toCharArray();

        for (char ch : arr) {
            if (map.containsKey(ch)) {
                Integer old = map.get(ch); //获取字符的个数
                map.put(ch, old + 1);
            } else {
                map.put(ch, 1);
            }
        }
        ArrayList<Map.Entry<Character,Integer>> list=new ArrayList<Map.Entry<Character, java.lang.Integer>>();

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
               list.add(entry);
        }

        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        System.out.println(list);//降序list
        //取并列value值
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i).getValue() == list.get(0).getValue()){
                System.out.println(list.get(i));
            }
        }
        System.out.println(list.get(0));

collections.max()+map.values()来解决就简单多了

        String str = "sdnasjhdasdaksnfcjdshdfudfhaosinfdaaasjncxkjz";
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        char[] arr = str.toCharArray();

        for (char ch : arr) {
            if (map.containsKey(ch)) {
                Integer old = map.get(ch); //获取字符的个数
                map.put(ch, old + 1);
            } else {
                map.put(ch, 1);
            }
        }
        List<Integer> valuesList = new ArrayList<Integer>(map.values());
        Integer i = Collections.max(map.values());
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            if(entry.getValue()==i){
                System.out.println(entry.getKey()+"---"+entry.getValue());
            }
        }

这个方法也不错

		String str = "sdnasjhdasdaksnfcjdshdfudfhaosinfdaaasjncxkjz";
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        while(str.length()>0){
            char c=str.charAt(0);
            str=str.substring(1);
            System.out.println(str);
            Integer count=map.get(c);
            if(count==null){
                map.put(c,1);

            }else{
                map.put(c,count+1);
            }
        }
        Collection<Integer> values=map.values();
        Integer max= Collections.max(values);
        Set<Character> keySet=map.keySet();
        for(Character ch:keySet){
            if(max.equals(map.get(ch))){
                System.out.println(ch+"-------"+max);
            }
        }

你可能感兴趣的:(java)