关于leetcode:leetcode之转变日期格式

本文次要记录一下leetcode之转变日期格局

题目

给你一个字符串 date ,它的格局为 Day Month Year ,其中:

Day 是汇合 {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} 中的一个元素。
Month 是汇合 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"} 中的一个元素。
Year 的范畴在 ​[1900, 2100] 之间。
请你将字符串转变为 YYYY-MM-DD 的格局,其中:

YYYY 示意 4 位的年份。
MM 示意 2 位的月份。
DD 示意 2 位的天数。
 

示例 1:

输出:date = "20th Oct 2052"
输入:"2052-10-20"
示例 2:

输出:date = "6th Jun 1933"
输入:"1933-06-06"
示例 3:

输出:date = "26th May 1960"
输入:"1960-05-26"
 

提醒:

给定日期保障是非法的,所以不须要解决异样输出。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reformat-date
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

class Solution {
     Map<String, String> monthMap = new HashMap<>(){{
            put("Jan", "01");
            put("Feb", "02");
            put("Mar", "03");
            put("Apr", "04");
            put("May", "05");
            put("Jun", "06");
            put("Jul", "07");
            put("Aug", "08");
            put("Sep", "09");
            put("Oct", "10");
            put("Nov", "11");
            put("Dec", "12");
        }};

    public String reformatDate(String date) {
        String[] dates = date.split(" ");
        String month = monthMap.get(dates[1]);
        String year = dates[2];
        String day = dates[0].substring(0,dates[0].length()-2);
        if (day.length() == 1) {
            day = "0"+ day;
        }
        return year+"-"+month+"-"+day;
    }
}

小结

这里应用HashMap来映射英文的month,而后针对日期移除后缀,最初针对天有余两位的往前补零,最初拼接为指定的格局。

doc

  • [转变日期格局(https://leetcode-cn.com/probl…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理