题目描述
一直两个字符串A,B。 连续进行读入n次。 每次读入的字符串都为A|B。 输出读入次数最多的字符串。
输入描述:
第一行输入整数n.(1<=n<=100)。 以下n行读入n个字符串。
输出描述:
输出读入次数最多的字符串,如果两个字符串读入次数相同输出,”dogfall”。
示例
// 请关闭中文输入法,用英文的字母和标点符号。
// 如果你想运行系统测试用例,请点击【执行代码】按钮,如果你想提交作答结果,请点击【提交】按钮,
// 注意:除答案外,请不要打印其他任何多余的字符,以免影响结果验证
// 本OJ系统是基于 OxCoder 技术开发,网址:www.oxcoder.com
// 模版代码提供基本的输入输出框架,可按个人代码习惯修改
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str_0 = scan.nextLine().trim();
int n = Integer.parseInt(str_0);
ArrayList<String> vector = new ArrayList<>();
for (int i = 0; i < n; i++){
String str_1 = scan.nextLine().trim();
vector.add(str_1);
}
scan.close();
String result = solution(n, vector);
System.out.println(result);
}
public static String solution(int n, ArrayList<String> vector){
String result = "";
// TODO: 请在此编写代码
// 非空判断
if (vector.size() == 0 || vector.contains("")) {
return "dogfall";
}
HashMap<String, Long> strMap = new HashMap<>((int) (n / 0.75 + 1));
for (String s : vector) {
if (strMap.containsKey(s)) {
Long value = strMap.get(s);
// 字符串重复出现 value +1L
strMap.replace(s, value += 1L);
} else {
strMap.put(s, 1L);
}
}
// 获取最大value
Collection<Long> values = strMap.values();
Long maxValue = Collections.max(values);
// 过滤:过滤出拥有maxValue值的数量,如果拥有数量大于1 则判断为平局"dagfall"
int size = (int) strMap.values().stream().filter(maxValue::equals).count();
if (size == 0 || size > 1) {
result = "dogfall";
} else {
// 根据value获取map的key
for (Map.Entry<String, Long> entry : strMap.entrySet()) {
if (entry.getValue().equals(maxValue)) {
result = entry.getKey();
}
}
}
return result;
}
}