【leetcode_easy_string】1507. Reformat Date

problem

1507. Reformat Date

solution#1: 使用map;使用函数;

code:

class Solution {
public:
    unordered_map<string, string> months = {{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"},{"Apr", "04"}, {"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"}, {"Sep", "09"},{"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}};
    string reformatDate(string date) {   
        string res = "";
        if(date.size()==12)
        {
            // res = date.substr(8,4) + "-" + mon(date.substr(4, 3)) + "-0" + date.substr(0,1);
            res = date.substr(8,4) + "-" + months[date.substr(4, 3)] + "-0" + date.substr(0,1);

        }
        else
        {
           // res = date.substr(9,4) + "-" + mon(date.substr(5, 3)) + "-" + date.substr(0,2);
           res = date.substr(9,4) + "-" + months[date.substr(5, 3)] + "-" + date.substr(0,2);
        }
        return res;
    }
    string mon(string s)
    {
        string res = "";
        if(s=="Jan") res = "01";
        else if(s=="Feb") res = "02";
        else if(s=="Mar") res = "03";
        else if(s=="Apr") res = "04";
        else if(s=="May") res = "05";
        else if(s=="Jun") res = "06";
        else if(s=="Jul") res = "07";
        else if(s=="Aug") res = "08";
        else if(s=="Sep") res = "09";
        else if(s=="Oct") res = "10";
        else if(s=="Nov") res = "11";
        else if(s=="Dec") res = "12";
        return res;
    }
};

 注意,通过字符串长度区分日期;

参考

1. leetcode_easy_string_1507. Reformat Date;

posted on 2021-02-25 13:38  鹅要长大  阅读(93)  评论(0编辑  收藏  举报

导航