题解 | #字符统计#
字符统计
http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
例子:
输入:abddacd
TreeMap:{a=2, b=1, c=1, d=3}
输出:dabc
用Set去重并计算字符出现的次数;
用map存储字符和次数,key存储字符,value存次数,我选择TreeMap,因为它会自己排序,这样后面遍历按照字符出现的次数排序时,直接能把字符拿出来拼接即可。
定义一个变量maxCount存储字符出现次数最大的值。
用maxCount递减遍历,例子中字符d出现3次,则递减遍历3次。
用Map.Entry遍历TreeMap.entrySet(),判断当前的maxCount是否与map的value相等,相等则拼接字符。
代码实现:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String inStr = sc.nextLine();
Set<Character> set = new HashSet<Character>();
for(int i = 0;i<inStr.length();i++){
set.add(inStr.charAt(i));
}
int maxCount = 0;
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for(char c:set){
int count = getCharCount(inStr,c);
if(maxCount<count) {
maxCount = count;
}
map.put(c,count);
}
StringBuilder sb = new StringBuilder("");
while(maxCount > 0){
for(Map.Entry m : map.entrySet()) {
if(m.getValue().equals(maxCount)) {
sb.append(m.getKey());
}
}
maxCount--;
}
System.out.println(sb);
}
}
public static int getCharCount(String str,char c){
int count = 0;
for(int i = 0;i<str.length();i++){
if(str.charAt(i)==c){
count++;
}
}
return count;
}
}