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:
Input: date = "20th Oct 2052" Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933" Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960" Output: "1960-05-26"
Constraints:
In this approach, we will parse the given date string to extract the day, month, and year. We will then use a dictionary to map the month abbreviations to their respective numeric representations. Finally, the result is formatted to 'YYYY-MM-DD'.
This C solution involves splitting the input string into its components using sscanf, mapping the month to its numeric value, and then formatting it to the desired date format using sprintf. A fixed-size array is used for returning the formatted date.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1), as we simply parse a fixed-length string and perform constant time operations.
Space Complexity: O(1), for storing result and month mapping.
Here, we utilize a regular expression to extract the day, month, and year separately. This approach eliminates multiple string operations by capturing groups when matching patterns directly.
This C solution uses regular expressions to match and extract parts directly from the date string, reducing manual parsing efforts.
Python
Time Complexity: O(1), as regex processing and substring extraction are linear in relation to string length.
Space Complexity: O(1), with fixed allocation for regex and output.
| Approach | Complexity |
|---|---|
| String Parsing and Dictionary Mapping | Time Complexity: O(1), as we simply parse a fixed-length string and perform constant time operations. |
| Regular Expression and String Manipulation | Time Complexity: O(1), as regex processing and substring extraction are linear in relation to string length. |
LeetCode License Key Formatting Solution Explained - Java • Nick White • 6,124 views views
Watch 9 more video solutions →Practice Reformat Date with our built-in code editor and test cases.
Practice on FleetCode