zoukankan      html  css  js  c++  java
  • 用JAVA实现找出输入字符串中的出现次数最多的字符及其次数;

     1 //通过Map 类实现,通过键值对的方式,可以将输入的字符串的每一个字符,作为键,每个字符出现的次数作为值:如下:
     2 
     3 public class Find {
     4   public static void main(String[] args){
     5     String scan=new Scanner(System.in).nextLine();//获取键盘上输入的字符串;
     6     Map<Character,Integer> map = new HashMap<Character,Integer>();//新建一个HashMap对象;    
     7        //通过FOR循环,把String的键值存放到map
     8     for(int i=0;i<scan.length();i++){
     9       char temp=scan.charAt(i);//通过循环,找到字符串的每一位字符并存入到temp中;
    10       if(map.containsKey(temp)){//如果map里面有temp这个字符
    11         map.put(temp, map.get(temp)+1);//把temp的值加1;
    12       }else{//如果map里面没有temp这个字符,
    13         map.put(temp, 1);//把temp的值设为1;
    14       }
    15     }
    16 /*Collection c = map.entrySet();
    17 Iterator it = c.iterator();
    18 Map.Entry<Character, Integer> entry;
    19 while(it.hasNext()){
    20 entry = (Map.Entry<Character, Integer>) it.next();
    21 }
    22 */
    23     int maxnum = Collections.max(map.values());//调用Collections类的max方法,获取map的值的集合;并找出最大的那个值;
    24     Set<Character> set = new HashSet<Character>();//建立一个set对象
    25     for(Map.Entry<Character, Integer> entry1:map.entrySet()){ //通过集合的循环,把map的值放到entry1里,通过entry1找到值最大的maxnum的key;
    26         if(entry1.getValue()==maxnum){
    27            set.add(entry1.getKey());
    28         }
    29     }
    30 System.out.println("出现次数最多的字母为:"+set+" 最多出现次数为"+maxnum);
    31 
    32  }
    33 
    34 }
  • 相关阅读:
    递归和消去递归
    Time complexity analysis of algorithms
    algorithms中计算时间的渐近表示
    OAuth认证协议原理分析及同步消息到Twitter和Facebook使用方法
    javascript实现URL编码与解码
    before伪类的超有用应用技巧——水平菜单竖线分隔符
    在线工具(转)
    程序员小抄大全
    Web设计的速查卡(转)
    一个简单的AJAX示例(转)
  • 原文地址:https://www.cnblogs.com/lelexiong/p/8727419.html
Copyright © 2011-2022 走看看