给定字符串,求出现次数最多的那个字母及次数,如有多个重复则都输出

来源:互联网 发布:建筑工程造价软件 编辑:程序博客网 时间:2024/06/05 23:49
给定字符串,求出现次数最多的那个字母及次数,如有多个 重复则都输出。

eg,String data ="aaavzadfsdfsdhshdWashfasdf";

这是一道很基础的面试题,在别的博客上也看到关于该题的解答,但总体来说感觉所给出的解法都有点拖沓,于是自己又 想出来一种较为简洁高效的解法(自己认为,有问题的地方大家可以挑出来),大体思路是:

1. 先将字符串中以出现的字符为关键字,出现的次数为值存放到hashmap中
2. 设置一个list记录出现次数最多的字母,max记录出现最多的次数,遍历hashmap
(1)如果下一个字符的出现次数小于max,则continue,
(2)等于max,则添加到list
(3)大于max,清空list,更新max,list中添加该字符

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class CountOfChar {  
  2.     public static void main(String[] args) {  
  3.         //String data ="aaavzadfsdfsdhshdWashfasdf";  
  4.         String data = "aaaabbbbccccc";  
  5. Map<Character,Integer> countMap = new HashMap<Character,Integer>();  
  6.         for(int i=0;i<data.length();i++){  
  7.             char c = data.charAt(i);  
  8.             if(countMap.containsKey(c)){  
  9.                 countMap.put(c,countMap.get(c)+1); //统计每个字符出现的次数  
  10.             }else{  
  11.                 countMap.put(c, 1); //该字符第一次出现  
  12.             }  
  13.         }  
  14.           
  15.         for(Map.Entry<Character, Integer> me:countMap.entrySet()){  
  16.             System.out.println(me.getKey()+"\t" + me.getValue());  
  17.         }  
  18.           
  19.         LinkedList<Character> list=new LinkedList<Character>();  
  20.           
  21.         int max=0;  
  22.         for(Map.Entry<Character, Integer> me:countMap.entrySet()){  
  23.             if(me.getValue()<max){  
  24.                 continue;  
  25.             }  
  26.             if(me.getValue()==max){   
  27.                 list.add(me.getKey());  
  28.             }  
  29.             if(me.getValue()>max){  
  30.                 list.clear();  
  31.                 max=me.getValue();  
  32.                 list.add(me.getKey());  
  33.             }  
  34.         }  
  35.         System.out.println("++++++++++++++++++++++++++");  
  36.         for(Character c:list){  
  37.             System.out.println(c+"\t" + max);  
  38.         }  
  39.     }  
  40.       
  41. }  
0 0