[LeetCode] Latest Time by Replacing Hidden Digits

준규·2023년 3월 13일
0

1.문제


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.


hh:mm 형태의 문자열이 주어지고 특정 digit이 ? 처리되어있는 문자열일때 ?를 00:00~24:00 범위내에서 가장 늦은 시간으로 변경하여 리턴하는 문제이다.


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"

Example 3

Input: time = "1?:22"
Output: "19:22"

Constraints:

  • time is in the format hh:mm.
  • It is guaranteed that you can produce a valid time from the given string.

2.풀이

  1. 시 부분의 10의 자리수는 1의자리수가 3보다 크면 1 , 아니라면 2로 변경한다.
  2. 시 부분의 10의 자리수가 2이면 1의 자리를 3으로 , 10의 자리수가 1또는 0이면 9로 변경한다.
  3. 분 부분의 10의 자리수는 5로 변경한다.
  4. 분 부분의 1의 자리수는 9로 변경한다.

/**
 * @param {string} time
 * @return {string}
 */
const maximumTime = function (time) {
  // digit을 배열에 저장한다
  time = time.split("");

  // 시 부분의 1의자리수가 3보다 크면 1 , 아니라면 2로 변경
  if (time[0] == "?" && time[1] > 3) time[0] = 1;
  else if (time[0] == "?") time[0] = 2;

  // 시 부분의 10의 자리수가 2이면 1의 자리를 3으로 , 10의 자리수가 1또는 0이면 9로 변경
  if (time[1] == "?" && time[0] == 2) time[1] = 3;
  else if (time[1] == "?" && (time[0] == 1 || time[0] == 0)) time[1] = 9;

  // 분 부분의 10의 자리수가 ? 이면 5로 변경
  if (time[3] == "?") time[3] = 5;

  // 분 부분의 1의 자리수가 ? 이면 9로 변경
  if (time[4] == "?") time[4] = 9;

  // 문자열로 만들어서 리턴한다.
  return time.join("");
};

3.결과

profile
안녕하세요 :)

0개의 댓글