給你一個字串 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 位的天數,
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reformat-date
我的答案:
我真是太傻比了,分割字串寫的太冗余了,用stringstream可以直接分割字串,看來還是要加強流編程的學習;
另外,月份匹配的時候,其實可以用Map,字符做key,對應的數字做value
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; } };
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/172088.html
標籤:C++
上一篇:C++學習筆記-C++簡介
下一篇:學習第51天
