본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 1507. Reformat Date

반응형

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

map을 사용해본 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 한 문자열을 공백을 구분자로 잘라 vector <string>으로 반환하는 split 함수를 구현합니다. stringstream을 사용하면 됩니다.2. split된 문자열을 dateInfo에 저장합니다. key는 변환할 문자, value에는 변환될 문자를 저장할 monthMap, dayMap를 선언 후 맞는 형태로 저장합니다. 11th, 12th 외 숫자 1의 자리가 1또는 2라면 st, nd를 붙여야 됨에 주의합니다.

📔 풀이과정

split 된 dateInfo의 day, month, year에 해당하는 부분을 지역변수를 선언해 저장합니다.

📔 정답 출력 | 반환

변환된 형태의 date 문자열을 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<string> split(string input) {
        stringstream ss(input);
        string tmp;
        vector<string>res;
        while(getline(ss,tmp, ' ')) {
            res.push_back(tmp);
        }
        return res;
    }
    string reformatDate(string date) {
        vector <string> dateInfo = split(date);
        map <string, string> monthMap, dayMap;

        monthMap["Jan"] = "01", monthMap["Feb"] = "02", monthMap["Mar"] = "03", monthMap["Apr"] = "04";
        monthMap["May"] = "05", monthMap["Jun"] = "06", monthMap["Jul"] = "07", monthMap["Aug"] = "08";
        monthMap["Sep"] = "09", monthMap["Oct"] = "10", monthMap["Nov"] = "11", monthMap["Dec"] = "12";
        
        dayMap["1st"] = "01", dayMap["2nd"] = "02", dayMap["3rd"] = "03", dayMap["4th"] = "04", dayMap["5th"] = "05";
        dayMap["6th"] = "06", dayMap["7th"] = "07", dayMap["8th"] = "08", dayMap["9th"] = "09", dayMap["10th"] = "10";
        dayMap["11th"] = "11", dayMap["12th"] = "12", dayMap["13th"] = "13", dayMap["14th"] = "14", dayMap["15th"] = "15";
        dayMap["16th"] = "16", dayMap["17th"] = "17", dayMap["18th"] = "18", dayMap["19th"] = "19", dayMap["20th"] = "20";
        dayMap["21st"] = "21", dayMap["22nd"] = "22", dayMap["23rd"] = "23", dayMap["24th"] = "24", dayMap["25th"] = "25";
        dayMap["26th"] = "26", dayMap["27th"] = "27", dayMap["28th"] = "28", dayMap["29th"] = "29", dayMap["30th"] = "30";
        dayMap["31st"] = "31";

        string day = dayMap[dateInfo[0]];
        string month = monthMap[dateInfo[1]];
        string year = dateInfo[2];
        return year + "-" + month + "-" + day;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.