遍历String字符串,得到出现次数最多的字母

//There is no need to explain the code right?

package
com.hp.test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class CharacterCheck { public static void main(String[] args) { String str = "sdfwefwefp[kmlskdjfowefjowefnsdlkj"; char ca[] = str.toCharArray(); Map<Character, Integer> charMap = new HashMap<Character, Integer>(); int maxNum = 1; for(char c : ca){ if(charMap.containsKey(c)){ int preNum = charMap.get(c); charMap.put(c, preNum + 1); if(maxNum < (preNum + 1)){ maxNum = maxNum + 1; } } else { charMap.put(c, 1); } } Set<Character> keys = charMap.keySet(); for(char c : keys){ if(charMap.get(c) == maxNum){ System.out.println(c + " show up for " + charMap.get(c) + " times, is the biggest!"); } else { System.out.println(c + " show up for " + charMap.get(c) + " times!"); } } } }

 

posted on 2015-08-08 10:01  马铃豆  阅读(440)  评论(0编辑  收藏  举报

导航