給你一個字符串 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 位的天數。spa
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/reformat-date
code
個人答案:orm
我真是太傻比了,分割字符串寫的太冗餘了,用stringstream能夠直接分割字符串,看來仍是要增強流編程的學習;blog
另外,月份匹配的時候,其實能夠用Map,字符作key,對應的數字作valueleetcode
class Solution { public: string reformatDate(string date) { int pos=0; vector<string> dict{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; string datestr=""; string monthstr=""; string yearstr=""; for (pos;date.at(pos)!=' '; ++pos) { datestr.push_back(date.at(pos)); } pos++; for (pos;date.at(pos)!=' '; ++pos) { monthstr.push_back(date.at(pos)); } pos++; for (pos;pos<date.length(); ++pos) { yearstr.push_back(date.at(pos)); } for (int i = 0; i < 12; i++) if (monthstr == dict[i]) { monthstr = (i < 9) ? '0' + to_string(i+1) : to_string(i+1); break; } if (datestr.length()==3) datestr="0"+datestr.substr(0,1); else datestr=datestr.substr(0,2); return yearstr+'-'+monthstr+'-'+datestr; } };