题解 | #数字字符#

数字字符

https://www.nowcoder.com/practice/024c3b99edc34b84999c5830f748a841

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Scanner;

public class Main {
    private static HashMap<Integer, Integer> digitMap = new HashMap<Integer, Integer>(){{
        put(0, 0);
        put(1, 0);
        put(2, 0);
        put(3, 0);
        put(4, 0);
        put(5, 0);
        put(6, 0);
        put(7, 0);
        put(8, 0);
        put(9, 0);
    }};

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);

        while(in.hasNext()){
            solution(in);
        }
    }

    /**
     * 模拟法
     * 
     * 举例找规律
     * 
     * @param in
     */
    private static void solution(Scanner in){
        String digits = in.nextLine();

        int digit;
        for(char ch: digits.toCharArray()){
            digit = Integer.parseInt(String.valueOf(ch));
            digitMap.put(digit, digitMap.get(digit)+1);
        }

        List<Map.Entry<Integer, Integer>> digitCountList = new ArrayList<>(digitMap.entrySet());

        Collections.sort(digitCountList, (o1, o2) -> {
            if(o1.getValue().equals(o2.getValue())){
                return o1.getKey()-o2.getKey();
            }else{
                return o1.getValue()-o2.getValue();
            }
        });

        Map.Entry<Integer, Integer> firstEntry = digitCountList.get(0);
        Map.Entry<Integer, Integer> secondEntry = digitCountList.get(1);
        StringBuilder sb = new StringBuilder();
        if(firstEntry.getValue() == 0){
            if(firstEntry.getKey() == 0){
                if(secondEntry.getValue() == 0){
                    sb.append(secondEntry.getKey());
                }else{
                    sb.append(10);
                }
            }else{
                sb.append(firstEntry.getKey());
            }
        }else{
            if(firstEntry.getKey() == 0){
                for(int i=0; i<=secondEntry.getValue(); i++){
                    sb.append(secondEntry.getKey());
                }
            }else{
                for(int i=0; i<=firstEntry.getValue(); i++){
                    sb.append(firstEntry.getKey());
                }
            }
        }

        System.out.println(sb);
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 11:45
你不要过来啊啊啊啊啊啊啊
码农索隆:对面:“今天你不面也得面”
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:00
点赞 评论 收藏
分享
06-12 10:50
门头沟学院 Java
你的不定积分没加C:我怎么在学院群看到了同样的话
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务