跳转至

1507.Reformat Date

Tags: String Easy

Links: https://leetcode.com/problems/reformat-date/


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.

首先需要根据空格将字符串进行分割,也就是写一个split函数,应该用split的方法还在LeetCode 468和HDU-1062 Text Reverse,还有就是本题。这个在《字符串算法——split函数》总结了。

将字符串date以空格进行分割,提取出day, month, year,涉及monthday需要注意前导0,另外本体的月份其实并不需要自己手打,只需要将题目里的部分复制,直接初始化即可。

cnt的目的是为了确定究竟在处理daymonth还是year

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;
    }
};

解法二:使用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;
    }
};