题目描述
Given a date
string in the form Day Month Year
, where:
Day
is in the set{"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}
.Month
is in the set{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
.Year
is in the range[1900, 2100]
.
Convert the date string to the format YYYY-MM-DD
, where:
YYYY
denotes the 4 digit year.MM
denotes the 2 digit month.DD
denotes the 2 digit day.
样例
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
- The given dates are guaranteed to be valid, so no error handling is necessary.
算法1
(字符串split) $O(n)$
将字符串date
以空格进行分割,提取出day, month, year
,涉及month
和day
需要注意前导0,另外本题的月份其实并不需要自己手打,只需要将题目里的部分复制,直接初始化即可。
cnt
的目的是为了确定究竟在处理day
,month
还是year
。
C++ 代码
class Solution {
vector<string> seq = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
public:
string reformatDate(string date) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
unordered_map<string, int> um;
for (int i = 0; i < 12; ++i) um[seq[i]] = i + 1;
istringstream is(date);
string tmp, res;
int cnt = 0;
while (getline(is, tmp, ' ')) {
++cnt;
if (cnt == 1) {
if (tmp.size() == 3) res.push_back('0');
res += tmp.substr(0, tmp.size() - 2);
}
else if (cnt == 2) {
res = to_string(um[tmp]) + "-" + res;
if (um[tmp] < 10) res = "0" + res;
}
else {
res = tmp + "-" + res;
}
}
return res;
}
};
算法2
当然也可以用stringstream
来实现按照空格分割字符串
class Solution {
vector<string> seq = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
public:
string reformatDate(string date) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
unordered_map<string, int> um;
for (int i = 0; i < 12; ++i) um[seq[i]] = i + 1;
stringstream ss(date);
string tmp, res;
//extract day
ss >> tmp;
if (tmp.size() == 3) res.push_back('0');
res += tmp.substr(0, tmp.size() - 2);
//extract month
ss >> tmp;
res = to_string(um[tmp]) + "-" + res;
if (um[tmp] < 10) res = "0" + res;
//extract year
ss >> tmp;
res = tmp + "-" + res;
return res;
}
};