【简单】字符串字母数统计
输入1: AAABBC
输出1: A3B2C
输入2:DDBCAA
输出2:A2B1C1D2
解析:首先想到的是用一个hashmap来存储每个字母的统计,然后再对hashmap的关键字进行排序
按照字母顺序输出打印,实现代码如下:
public static String charCount(String str) { String res = ""; Map<String, Integer> map = new HashMap<>(); char[] charArr = str.toCharArray(); for(char c : charArr){ if((c >='a'&& c < 'z')|| (c>='A' && c <= 'Z')){ String key = String.valueOf(c); if(map.containsKey(key)){ map.put(key,map.get(key) + 1); }else{ map.put(key,1); } }else{ continue; } } List<String> strList = new ArrayList<String>(); strList.addAll(map.keySet()); Collections.sort(strList); for(String charStr : strList){ res += charStr + map.get(charStr); } return res; } public static void main(String[] args){ System.out.println(charCount("AAABBC")); System.out.println(charCount("A")); System.out.println(charCount("AA")); System.out.println(charCount("ABC")); System.out.println(charCount("AA55AdfereadfB44BC4")); }