列表

详情


1507. 转变日期格式

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

请你将字符串转变为 YYYY-MM-DD 的格式,其中:

 

示例 1:

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

示例 2:

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

示例 3:

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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: string reformatDate(string date) { } };

golang 解法, 执行用时: 0 ms, 内存消耗: 2 MB, 提交时间: 2020-11-11 22:49:22

func reformatDate(date string) string {
	parts := strings.Split(date, " ")
	Day, _ := strconv.Atoi(parts[0][:len(parts[0])-2])
	Months := map[string]int{
		"Jan": 1,
		"Feb": 2,
		"Mar": 3,
		"Apr": 4,
		"May": 5,
		"Jun": 6,
		"Jul": 7,
		"Aug": 8,
		"Sep": 9,
		"Oct": 10,
		"Nov": 11,
		"Dec": 12,
	}
	Month := Months[parts[1]]
	Year, _ := strconv.Atoi(parts[2])
	return fmt.Sprintf("%d-%02d-%02d", Year, Month, Day)
}

python3 解法, 执行用时: 36 ms, 内存消耗: 13.4 MB, 提交时间: 2020-11-11 22:43:27

class Solution:
    def reformatDate(self, date: str) -> str:
        day, m, y = date.split(' ')
        day = int(day[:-2])
        mm = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        m = mm.index(m) + 1
        return f'{y}-{m:02d}-{day:02d}'

上一题