1507转变日期格式

    科技2022-07-13  112

    题目描述: 给你一个字符串 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”

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

    方法1: 主要思路: (1)直接给定的字符串进行拆分,拆分成对应的年月日,然后再分别拼接即可;

    class Solution { public: string reformatDate(string date) { unordered_map<string,string> mp; //月份表示之间的映射关系 mp["Jan"]="01"; mp["Feb"]="02"; mp["Mar"]="03"; mp["Apr"]="04"; mp["May"]="05"; mp["Jun"]="06"; mp["Jul"]="07"; mp["Aug"]="08"; mp["Sep"]="09"; mp["Oct"]="10"; mp["Nov"]="11"; mp["Dec"]="12"; string day; int pos=0; //拆分出天 while(date[pos]!='t'&&date[pos]!='s'&&date[pos]!='n'&&date[pos]!='r'){ day+=date[pos]; ++pos; } while(date[pos]!=' '){ ++pos; } //拆分出月 string month=date.substr(pos+1,3); month=mp[month];//并将月份进行映射 //拆分出年 string year=date.substr(pos+5,4); //对年月日进行拼接 string res; res+=year; res+='-'; res+=month; res+='-'; if(day.size()==1){ res+='0'; } res+=day; return res; } };
    Processed: 0.010, SQL: 8