给你一个字符串 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; } };