给定字符串,求出现次数最多的那个字母及次数,如有多个 重复则都输出。
eg,String data ="aaavzadfsdfsdhshdWashfasdf";
这是一道很基础的面试题,在别的博客上也看到关于该题的解答,但总体来说感觉所给出的解法都有点拖沓,于是自己又 想出来一种较为简洁高效的解法(自己认为,有问题的地方大家可以挑出来),大体思路是:
1. 先将字符串中以出现的字符为关键字,出现的次数为值存放到hashmap中
2. 设置一个list记录出现次数最多的字母,max记录出现最多的次数,遍历hashmap
(1)如果下一个字符的出现次数小于max,则continue,
(2)等于max,则添加到list
(3)大于max,清空list,更新max,list中添加该字符
- public class CountOfChar {
- public static void main(String[] args) {
- //String data ="aaavzadfsdfsdhshdWashfasdf";
- String data = "aaaabbbbccccc";
- Map<Character,Integer> countMap = new HashMap<Character,Integer>();
- for(int i=0;i<data.length();i++){
- char c = data.charAt(i);
- if(countMap.containsKey(c)){
- countMap.put(c,countMap.get(c)+1); //统计每个字符出现的次数
- }else{
- countMap.put(c, 1); //该字符第一次出现
- }
- }
- for(Map.Entry<Character, Integer> me:countMap.entrySet()){
- System.out.println(me.getKey()+"\t" + me.getValue());
- }
- LinkedList<Character> list=new LinkedList<Character>();
- int max=0;
- for(Map.Entry<Character, Integer> me:countMap.entrySet()){
- if(me.getValue()<max){
- continue;
- }
- if(me.getValue()==max){
- list.add(me.getKey());
- }
- if(me.getValue()>max){
- list.clear();
- max=me.getValue();
- list.add(me.getKey());
- }
- }
- System.out.println("++++++++++++++++++++++++++");
- for(Character c:list){
- System.out.println(c+"\t" + max);
- }
- }
- }