一. 题目
-
题目
-
示例
二. 方法一: 第一思路
-
解题思路
但是写日期的hash表太过麻烦, 而且中途还写错了"21"和"22"的日期 -
解题代码
def reformatDate(self, date: str) -> str: day = {"1st": "01", "2nd": "02", "3rd": "03", "4th": "04", "5th": "05", "6th": "06","7th": "07", "8th": "08", "9th": "09", "10th": "10", "11th": "11", "12th": "12", "13th": "13", "14th": "14", "15th": "15", "16th": "16", "17th": "17", "18th": "18", "19th": "19", "20th": "20", "21st": "21", "22nd": "22", "23rd": "23", "24th": "24", "25th": "25", "26th": "26", "27th": "27", "28th": "28", "29th": "29", "30th": "30", "31st": "31"} month = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"} time = date.split(" ") return time[2] + "-" + month[time[1]] + "-" + day[time[0]]
-
分析
三. 方法二: 优化
-
解题思路
由于日的后面都有一个2位的后缀, 并且最终用0补位. 所以可以先去掉后缀, 再用0补足2为即可,
这样就不用对日进行hash表的创建 -
解题代码
def reformatDate(self, date: str) -> str: month = {"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06", "Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"} time = date.split(" ") return time[2] + "-" + month[time[1]] + "-" + time[0][:-2].zfill(2)
-
分析