LeetCode 题解工作台

转变日期格式

给你一个字符串 date ,它的格式为 Day Month Year ,其中: Day 是集合 {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"} 中的一个元素。 Month 是集合 {"Jan", "Feb", "Mar", "Apr", "May"…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

将字符串按空格分割为三个部分,分别为 `day`、`month` 和 `year`,然后拼接为 `YYYY-MM-DD` 的格式。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 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"

 

提示:

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

解题思路

方法一:模拟

将字符串按空格分割为三个部分,分别为 daymonthyear,然后拼接为 YYYY-MM-DD 的格式。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def reformatDate(self, date: str) -> str:
        s = date.split()
        s.reverse()
        months = " JanFebMarAprMayJunJulAugSepOctNovDec"
        s[1] = str(months.index(s[1]) // 3 + 1).zfill(2)
        s[2] = s[2][:-2].zfill(2)
        return "-".join(s)
speed

复杂度分析

指标
时间complexity is O(1) because the input size is fixed and splitting plus mapping operations are constant. Space complexity is O(1) as only a few variables and a fixed-size dictionary are used.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for explicit handling of day suffixes and zero-padding in the solution.

  • question_mark

    Verify that month abbreviation mapping covers all months and handles case consistently.

  • question_mark

    Expect a simple string-based solution without relying on built-in date libraries.

warning

常见陷阱

外企场景
  • error

    Forgetting to remove day suffixes before padding, leading to incorrect day formatting.

  • error

    Incorrect mapping of month abbreviations or typos in the dictionary.

  • error

    Failing to pad single-digit months or days, resulting in invalid YYYY-MM-DD format.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Input dates could include varying day suffixes or whitespace requiring careful trimming.

  • arrow_right_alt

    Month names could appear in full form rather than three-letter abbreviations.

  • arrow_right_alt

    Extensions could involve converting multiple date strings in a list efficiently.

help

常见问题

外企场景

转变日期格式题解:String-driven solution … | LeetCode #1507 简单