LeetCode 1507: Reformat Date Solution
Master LeetCode problem 1507 (Reformat Date), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1507. Reformat Date
Problem Explanation
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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1507 (Reformat Date)?
This page provides optimized solutions for LeetCode problem 1507 (Reformat Date) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1507 (Reformat Date)?
The time complexity for LeetCode 1507 (Reformat Date) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1507 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1507 in Java, C++, or Python.