LeetCode 1507: Reformat Date
Problem Description
Explanation:
To solve this problem, we can split the input date string into day, month, and year components. Then, we can convert the month string into its corresponding numeric value. Finally, we can format the date in the required YYYY-MM-DD format.
- Split the input date string by spaces to extract day, month, and year.
- Convert the month string into its corresponding numeric value using a hashmap.
- Remove the suffix from the day string and convert it to an integer.
- Format the date into the required YYYY-MM-DD format.
Time Complexity:
- The time complexity of this solution is O(1) because the number of possible days, months, and years is limited.
Space Complexity:
- The space complexity is O(1) as we are using a constant amount of extra space regardless of the input size.
:
Solutions
class Solution {
public String reformatDate(String date) {
String[] parts = date.split(" ");
String day = parts[0];
String month = parts[1];
String year = parts[2];
HashMap<String, String> monthMap = new HashMap<>();
monthMap.put("Jan", "01");
monthMap.put("Feb", "02");
monthMap.put("Mar", "03");
monthMap.put("Apr", "04");
monthMap.put("May", "05");
monthMap.put("Jun", "06");
monthMap.put("Jul", "07");
monthMap.put("Aug", "08");
monthMap.put("Sep", "09");
monthMap.put("Oct", "10");
monthMap.put("Nov", "11");
monthMap.put("Dec", "12");
String monthNum = monthMap.get(month);
String dayNum = day.substring(0, day.length() - 2);
if (dayNum.length() == 1) {
dayNum = "0" + dayNum;
}
return year + "-" + monthNum + "-" + dayNum;
}
}
Loading editor...