【依图科技】2023.09.07 笔试第二题回忆记录版
题目描述回忆版:输入字符串数组,输出出现次数第二多的小写字母及其出现次数,如果没有第二多的(即都并列多)返回空;如果有并列的,以字母排序。
ep:
输入:["abb","cdd34&","#$2d3ddaa"]
输出:a-3
package com.example;// 本题为考试单行多行输入输出规范示例,无需提交,不计分。
import java.util.*;
//题目:输入一个String[],输出出现次数第二多的小写字母,如果没有第二少的返回空;如果有并列的,以字母排序。
public class ToFindTheSecondLowerCharacter {
public static String getAns(String[] ss ){
HashMap<Character,Integer> hm = new HashMap<>();
for (int i = 0; i < ss.length; i++) {
String a = ss[i];
for (int j = 0; j < a.length(); j++) {
char ch = a.charAt(j);
if(ch>='a'&&ch<='z') {
hm.put(ch, hm.getOrDefault(ch, 0) + 1);
}
}
}
//对hash表进行自定义排序,从大到小,如果出现次数相同,根据ASC2码排序,
ArrayList<Map.Entry<Character, Integer>> entries = new ArrayList<>(hm.entrySet());
// entries.sort(((o1, o2) -> o2.getValue().compareTo(o1.getValue())));
entries.sort(new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
if (o1.getValue()> o2.getValue()){
return o1.getValue();
}else if (o1.getValue().equals(o2.getValue())){
return o1.getKey()>o2.getKey()? o1.getValue() : o2.getValue();
}
return o2.getValue();
}
});
//以下处理边界条件,提高测试用例通过率
if (entries.size()<2||entries==null){
return " ";
}
int index = 1;
while(index<entries.size()){
if(entries.get(index-1).getValue().equals(entries.get(index).getValue())){
index++;
continue;//跳出当前循环
}
Character key = entries.get(index).getKey();
Integer value = entries.get(index).getValue();
return key+"-"+value;
}
return " ";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例
int a = in.nextInt();
String[] ss = new String[a];
for (int i = 0; i < a; i++) {
String s = in.next();
ss[i] = s;
}
System.out.println(getAns(ss));
}
}
}
#在找工作求抱抱#0基础刷题笔试日记 文章被收录于专栏
记录2023年秋招开始刷题以来的笔试复盘记录