• 统计一个字符串中出现次数最多的字符,并统计次数


    最近同事出去面试,回来问我一道笔试题(统计一个字符串中出现次数最多的字符,并统计次数)

    大家看到这个题目,应该立刻想到,这道题是对java集合运用的考察。我的解答如下代码所示:

              String str = "aaaaaaaaabbbbbbbbbbbbbbbbbbbbbcccddddddddeffg";
    		char[] charArray = str.toCharArray();
    		Map<Character,Integer> map = new HashMap<Character,Integer>();
    		for(char c : charArray){
    			if(map.containsKey(c)){
    				map.put(c, map.get(c)+1);
    			}else{
    				map.put(c, 1);
    			}
    		}
    		
    		Set<Entry<Character, Integer>> entrySet = map.entrySet();
    		Comparator<Entry<Character, Integer>> cr = new Comparator<Map.Entry<Character,Integer>>() {
    			@Override
    			public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
    				if(o1.getValue() > o2.getValue()){
    					return 1;
    				}else if(o1.getValue() == o2.getValue()){
    					return 0;
    				}else{
    					return -1;
    				}
    			}
    		};
    		List<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(entrySet);
    		Collections.sort(list, cr);
    		Entry<Character, Integer> e = list.get(list.size()-1);
    		System.out.println("出现次数最多的字符:::"+e.getKey());
    		System.out.println("出现次数:::"+e.getValue());
    

      

    结果如下:

    符合我们的预期,这只是我想到的一种方法,也许还有其他更好的方法

    总结:

      虽然只有几十行的代码,但是涉及到的知识点还真不少:

      1.map集合的运用

      2.java.util.Comparator接口的运用(自定义排序规则)

      3.set 转list

      4.Collections.sort排序

      

  • 相关阅读:
    oracle mybatis 模糊查询
    IntelliJ IDEA各种引入jar包的方式及其关系
    eclipse中新建Java工程的三个JRE选项区别
    @Autowired注解和@resource注解的区别
    结合测试,黑盒测试
    Oracle左连接、右连接、全外连接以及(+)号用法
    samePropertyValuesAs()
    Collection.sort 的用法
    junit withcapture
    单元测试
  • 原文地址:https://www.cnblogs.com/hjw-zq/p/9049430.html
Copyright © 2020-2023  润新知