找出给定字符串中出现最多的字符和次数
一、背景介绍
这是我遇到的一道面试题,分享一下自己的想法,希望能够有所帮助。使用了Java中的HashMap,统计每个字符出现的次数,时间复杂度为O(n)。
二、算法实现
/** * @author Mist Lee * 输入一个字符串,找出这个字符串中出现最多的字符和个数*/ public class MaxDupilicationCount { public static void main(String[] args) { String str = "abcdaajflkfadhjfdhklgfdj"; HashMap<Character,Integer> hm = new HashMap<Character,Integer>(); Character maxChar = null; Integer maxCount = 0; for(Character c : str.toCharArray()) { if(hm.containsKey(c)) { hm.put(c, hm.get(c) + 1); }else { hm.put(c, 1); } } for(Entry<Character,Integer> entry : hm.entrySet()) { if(entry.getValue() > maxCount) { maxChar = entry.getKey(); maxCount = entry.getValue(); } } System.out.println("maxChar=" + maxChar); System.out.println("maxCount=" + maxCount); } }

浙公网安备 33010602011771号