LeetCode 1507. 转变日期格式

目录结构

1.题目

2.题解


1.题目

给你一个字符串 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 位的天数。

示例:

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


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


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

提示:

  • 给定日期保证是合法的,所以不需要处理异常输入。

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

2.题解

public class Solution1507 {


    @Test
    public void test1507() {
        String date = "20th Oct 2052";
        System.out.println(reformatDate(date));
    }

    public String reformatDate(String date) {
        String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < 12; i++) {
            map.put(months[i], i + 1);
        }
        String year = date.split(" ")[2];
        String month = String.valueOf(map.get(date.split(" ")[1]));
        if (month.length() == 1) {
            month = "0" + month;
        }
        String day = getDay(date.split(" ")[0]);
        if (day.length() == 1) {
            day = "0" + day;
        }
        return year + "-" + month + "-" + day;
    }

    public String getDay(String day) {
        int d = 0;
        for (char c : day.toCharArray()) {
            if (Character.isDigit(c)) {
                d = d * 10 + c - '0';
            }
        }
        return String.valueOf(d);
    }
}
  • 时间复杂度:O(1)
  • 空间复杂度:O(1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值