a×最大时间

发布于:2024-09-18 ⋅ 阅读:(13) ⋅ 点赞:(0)

题目描述

给定一个数组,里面有6个整数,求这个数组能够表示的最大 24 进制的时间是多少,输出这个时间,无法表示输出 invalid.

输入描述

输入为一个整数数组,数组内有六个整数。
输入整数数组长度为6,不需要考虑其它长度,元素值为0或者正整数,6 个数字每个数字只能使用一次。

输出描述

输出为一个 24 进制格式的时间,或者字符串"invalid".

我也不是很明白,有的步骤为什么这么写,但是大体流程是知道的,可能练习不够,还需多加练习吧

 //[0,2,3,0,5,6]
public class 最大时间Main {
    private static final Pattern c = Pattern.compile("(([01][0-9])|([2][0-3])):([0-5][0-9]):([0-5][0-9])");
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        Integer[] arr = Arrays.stream(s.substring(1, s.length() - 1).split(","))
                .map(Integer::parseInt)
                .toArray(Integer[]::new);
 
        System.out.println(getResult(arr));
    }
 
    public static String getResult(Integer[] arr) {
        ArrayList<String> res = new ArrayList<>();
        dfs(arr, new boolean[arr.length], new LinkedList<>(), res);
 
        if (res.isEmpty()) return "invalid";
        Collections.sort(res, Collections.reverseOrder());
        return res.get(0);
    }
 
    public static void dfs(Integer[] arr, boolean[] used, LinkedList<Integer> path, ArrayList<String> res) {
        int pathLength = path.size();
        if (pathLength == arr.length) {
            Integer[] t = path.toArray(new Integer[0]);
            String time = t[0] + "" + t[1] + ":" + t[2] + "" + t[3] + ":" + t[4] + "" + t[5];
 
            if (c.matcher(time).matches()) res.add(time);
            return;
        }
 
        for (int i = 0; i < arr.length; i++) {
            if (!used[i]) {
                path.add(arr[i]);
                used[i] = true;
                dfs(arr, used, path, res);
                used[i] = false;
                path.removeLast();
            }
        }
    }
}