Leetcode 1507. 转变日期格式
题目:
给你一个字符串 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"
提示:
- 给定日期保证是合法的,所以不需要处理异常输入。
代码实现:
class Solution {
public:
const vector<string> month = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
// 匹配月份 并进行转化为 0x 形式
string getMonth(const string& m){
int res = 0;
for(int i = 0; i < month.size(); ++i){
if(m == month[i]) { res = i + 1; break;}
}
if(res < 10) return "0" + to_string(res);
return to_string(res);
}
string reformatDate(string date) {
stringstream ss(date); // stringstream 读取 d dd mm yy
int d;
string dd, mm, yy;
ss >> d >> dd >> mm >> yy;
mm = getMonth(mm);
dd = to_string(d);
return yy + "-" + mm + "-" + (d < 10 ? "0": "") + dd; // dd 进行转化 0x 形式
}
};