Latest Time by Replacing Hidden Digits

You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).

The valid times are those inclusively between 00:00 and 23:59.

Return the latest valid time you can get from time by replacing the hidden digits.

Example 1:

Input: time = "2?:?0"
Output: "23:50"
Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.

Example 2:

Input: time = "0?:3?"
Output: "09:39"

Approach

Java

public class LatestTime {
    public static void main(String[] args) {

        String time = "2?:?0";

        System.out.println(maximumTime(time));
    }

    static String maximumTime(String time) {

        String res = "";
        if (time.charAt(0) == '?' && time.charAt(1) == '?') {
            res += "2";
            res += "3";
        } else if (time.charAt(0) == '?') {
            if (time.charAt(1) >= '4')
                res += "1";
            else
                res += "2";
            res += time.charAt(1);

        } else if (time.charAt(1) == '?') {
            res += time.charAt(0);
            if (time.charAt(0) == '2')
                res += "3";
            else
                res += "9";

        }
        else
        {
            res+=time.charAt(0);
            res+=time.charAt(1);
        }
        res += ":";
        if (time.charAt(3) == '?')
            res += "5";
        else
            res += time.charAt(3);
        if (time.charAt(4) == '?')
            res += "9";
        else
            res += time.charAt(4);
        return res;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

string maximumTime(string time)
{

    if (time[0] == '?' and time[1] == '?')
    {
        time[0] = '2';
        time[1] = '3';
    }
    else if (time[0] == '?')
    {
        time[0] = (time[1] >= '4') ? '1' : '2';
    }
    else if (time[1] == '?')
    {
        time[1] = (time[0] == '2') ? '3' : '9';
    }

    if (time[3] == '?')
        time[3] = '5';
    if (time[4] == '?')
        time[4] = '9';
    return time;
}

int main()
{
    string time = "2?:?0";

    cout << maximumTime(time<< "\n";

    return 0;
}


No comments:

Post a Comment