[Leet Code] Reformat Date

Leetcode: https://leetcode.com/problems/reformat-date/

Problem:

Given a date string in the form Day Month Year, where:

  • Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
  • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
  • Year is in the range [1900, 2100].

Convert the date string to the format YYYY-MM-DD, where:

  • YYYY denotes the 4 digit year.
  • MM denotes the 2 digit month.
  • DD denotes the 2 digit day.

Example 1:

Example 2:

Example 3:

Solution:

Explanation:

We create a list of dates — the dates are already almost sorted in their index numbers, jan at the moment is sitting on index 0, when in fact it is the first month, so all we’ll have to do is month_lookup + 1 to get the real index of the month.

To get the year, we simply take the last 4 characters of the date string, this is done by: date[-4:]

The month will always be three characters, so again, we can just do date[-8:-5] to get the month with letters, then we simply find the index of this result in our month_lookup list and + 1 to get the real value of the month.

Then we do a check to make sure that the month has two digits, if it’s less than 0, we prepend a “0” to it.

For the day, there will be many ways to do this, my method is that I take the first two characters of the string, and if it’s a digit, that means that it’s any date in double figures(10,11,12..31), but if not, then it’s any date in single figures (1,2,3,4,5) so I return my answer based on that if statement.

--

--

Learning, and posting my findings!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store