题目:字符统计
对字符中的 各个英文字符(大小写分开统计),数字,空格进行统计,并按照统计个数由多到少输出,如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。
输入例子:
aadddccddc
输出例子:
dca
关于HashMap和TreeMap的一些注意:
TreeMap构造方法中的Comparator只能对key排序,不能对Map.Entry排序。
Collectons.sort()方法只能对List排序,不能对Set排序。
import java.util.*;
public class Main{
public static HashMap<Character,Integer> map=new HashMap();
public static void main(String[] args){
Scanner in=new Scanner(System.in);
while(in.hasNext()){
String s=in.nextLine();
HashMap<Character,Integer> map=new HashMap();
for(int i=0;i<s.length();i++){
if(s.charAt(i) >= 'A'&&s.charAt(i) <= 'Z'||s.charAt(i) >= 'a'&&s.charAt(i) <= 'z'||s.charAt(i) >= '0'&&s.charAt(i) <= '9'||s.charAt(i) == ' '){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}else{
map.put(s.charAt(i),1);
}
}
}
Set<Map.Entry<Character,Integer>> set=map.entrySet();
ArrayList<Pair> array=new ArrayList();
for(Map.Entry<Character,Integer> entry: set){
array.add(new Pair(entry.getKey(),entry.getValue()));
}
Collections.sort(array,new Comparator<Pair>(){
public int compare(Pair first,Pair second){
if(first.count!=second.count){
return second.count-first.count;
}else{
return first.c-second.c;
}
}
});
StringBuilder sb=new StringBuilder();
for(Pair pair: array){
sb.append(pair.c);
}
System.out.println(sb.toString());
}
in.close();
}
static class Pair{
char c;
int count;
public Pair(char c,int count){
this.c=c;
this.count=count;
}
}
}
题目:合并表记录
输入描述:
先输入键值对的个数 然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
输入例子:
4 0 1 0 2 1 2 3 4
输出例子:
0 3 1 2 3 4
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
while(in.hasNext()){
int n=in.nextInt();
TreeMap<Integer,Integer> map=new TreeMap();
for(int i=0;i<n;i++){
int key=in.nextInt();
int value=in.nextInt();
if(!map.containsKey(key)){
map.put(key,value);
}else{
map.put(key,map.get(key)+value);
}
}
Set<Map.Entry<Integer,Integer>> set=map.entrySet();
for(Map.Entry<Integer,Integer> entry: set){
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
in.close();
}
}
这道题就是注意map视图的方法
Set<Map.Entry<Integer,Integer>> set=map.entrySet();