题目描述

给你一个字符串 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 的格式。

例如:date = "20th Oct 2052",输出 "2052-10-20"

解题思路

核心思想

这是一个简单的字符串解析与格式化问题。输入格式为 "Day Month Year",需要输出 "YYYY-MM-DD"

步骤

  1. 字符串分割:使用 split(" ") 将输入日期按空格分割为三个部分——日、月、年。
  2. 年份直接拼接:年份部分(dateArr[2])已经是数字字符串,直接使用。
  3. 月份转换:使用一个 HashMap 存储月份的英文缩写到数字的映射(如 "Jan" → "01"),通过查表快速转换。
  4. 日期处理:日期部分包含英文序数后缀("st", "nd", "rd", "th"),需要提取纯数字:
    • 如果日期长度为 3(即个位数如 "1st"),取第一个字符并在前面补 "0"
    • 如果日期长度为 4(即两位数如 "20th"),取前两个字符。
  5. 拼接输出:按 YYYY-MM-DD 格式用 StringBuilder 拼接。

示例说明

"20th Oct 2052" 为例:

  • 分割得到 ["20th", "Oct", "2052"]
  • Year = "2052"
  • Month = "Oct" → 查表得 "10"
  • Day = "20th" → 取前两个字符 "20"
  • 拼接结果:"2052-10-20"

复杂度分析

  • 时间复杂度O(1),输入长度固定,所有操作均为常数时间。
  • 空间复杂度O(1),除结果字符串外仅使用常数额外空间(HashMap 固定大小)。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package code.J1507;

import java.util.HashMap;
import java.util.Map;

public class J1507 {
static Map<String, String> monthMap = new HashMap<>();
static {
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");
}
public String reformatDate(String date) {
String[] dateArr = date.split(" ");
StringBuilder sb = new StringBuilder();
sb.append(dateArr[2]);
sb.append("-");
sb.append(monthMap.get(dateArr[1]));
sb.append("-");
if (dateArr[0].length() == 3) sb.append("0").append(dateArr[0].charAt(0));
else sb.append(dateArr[0], 0, 2);
return sb.toString();
}
}