题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
package OnlineTest.easy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class HJ102 {
public static void main(String[] args) throws IOException {
/*思路:
* (1)集合(字母,次数)
* (2)compartor比较器 */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder(br.readLine());
HashMap<String, Integer> hm = new HashMap<>();
for (int i = 0; i < sb.length(); i++) {
String s = String.valueOf(sb.charAt(i));
if (hm.containsKey(s)) {
int t = hm.get(s);
t++;
hm.put(s, t);
}
else {
hm.put(s, 1);
}
}
List<stringO> list = new LinkedList<>();
hm.forEach((k,v)->{
list.add(new stringO(k, v));
});
Collections.sort(list, new stringOComparator());
list.forEach(o->{
System.out.print(o.s);
});
}
}
class stringO{
int times;
String s;
public stringO(String s,int times) {
this.times = times;
this.s = s;
}
@Override
public String toString() {
return "stringO{" +
"times=" + times +
", s='" + s + '\'' +
'}';
}
}
class stringOComparator implements Comparator {
@Override
public int compare(Object obj1, Object obj2) {//参数要一致,才算
stringO o1 = (stringO) obj1;
stringO o2 = (stringO) obj2;
//次数大的排在前面
if (o1.times > o2.times) {
return -1;
} else if (o1.times < o2.times) {
return 1;
} else {
//比较ASCii
char c1 = o1.s.charAt(0);
char c2 = o2.s.charAt(0);
if (c1 > c2) {
return 1;
} else if (c1 < c2) {
return -1;
} else {
return 0;
}
}
}
}
查看23道真题和解析