- 문제 풀이
1. 주어진 문자열들을 split하여 년, 월, 일 별로 저장해둔다. (여기서 map을 사용하면 더 간단해짐)
2. 날짜가 말일(28일)이거나 하는 경우를 고려하여 개인정보 유효 날짜를 구한다.
3. 오늘 날짜와 비교하여 개인정보 유효 날짜가 오늘 날짜보다 더 이르면 "answer" vector에 현재 인덱스를 저장한다.
- 내가 작성한 코드
이 코드는 처음에 작성한 코드이다.
처음엔 이렇게 stoi() 함수를 사용하여 작성했다.
아직 아는 함수나 요령들이 많지 않아 기초적으로 접근했는데, 이런 방식으로 논리상의 오류는 없이 코드를 짜면 좋겠다만
경우의 수를 직접 모두 고려해주어야 해서 코드가 복잡해지는 어려움이 생겼다.
역시 미리 "." 나 " "을 기준으로 split해 문자열을 년, 월, 일로 나눠놓고 계산하는 방법이 더 간단하고 빠르게 문제를 해결할 수 있는 방법이라는 것을 깨달았다.
!! c++에서 제공하는 내장함수들 많이 활용하려 노력해보자 !!
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
vector<int> solution(string today, vector<string> terms, vector<string> privacies) {
vector<int> answer;
for(int i=0; i<privacies.size(); i++) {
int year;
int month;
int date;
for(int j=0; j<terms.size(); j++) {
if(privacies[i].at(11) == terms[j].at(0)) {
if( stoi(privacies[i].substr(5,2))+stoi(terms[j].substr(2,1)) <= 12) {
if( stoi(privacies[i].substr(8,2)) == 1 ) {
year = stoi(privacies[i].substr(0,4));
month = stoi(privacies[i].substr(5,2))+stoi(terms[j].substr(2,1))-1;
date = 28;
}
else {
year = stoi(privacies[i].substr(0,4));
month = stoi(privacies[i].substr(5,2))+stoi(terms[j].substr(2,1));
date = stoi(privacies[i].substr(8,2))-1;
}
}
else {
if( stoi(privacies[i].substr(8,2)) == 1 ) {
month = (stoi(privacies[i].substr(5,2)) + stoi(terms[j].substr(2,1)))%12
-1;
year = stoi(privacies[i].substr(0,4)) + (stoi(privacies[i].substr(5,2))
+stoi(terms[j].substr(2,1)))/12;
date = 28;
}
else {
year = stoi(privacies[i].substr(0,4)) + (stoi(privacies[i].substr(5,2))
+stoi(terms[j].substr(2,1)))/12;
month = (stoi(privacies[i].substr(5,2)) + stoi(terms[j].substr(2,1)))%12;
date = stoi(privacies[i].substr(8,2)) -1;
}
}
break;
}
}
if( year < stoi(today.substr(0,4)) ) {
answer.push_back(i+1);
}
else if( year == stoi(today.substr(0,4)) ) {
if( month < stoi(today.substr(5,2)) ) {
answer.push_back(i+1);
}
else if( month == stoi(today.substr(5,2)) ) {
if( date < stoi(today.substr(8,2)) ){
answer.push_back(i+1);
}
}
}
}
return answer;
}
내가 작성한 위 코드의 실행결과는 다음과 같다.
그냥 다음부터 이런 문제가 나오면 split, map 등을 사용하여 가장 간단한 방법으로 해결해보도록 해야겠다.
오늘은 시행착오이니 다음부터 발전하면 된다.
또 이 문제도 다시 더 간단한 방법으로 풀어봐야 겠다.
(그래도 이 기회를 통해 #include <string>에 내장되어 있는 stoi... 등의 함수에 대해 알 수 있었다.)

'프로그래머스' 카테고리의 다른 글
| 폰켓몬 - 프로그래머스, c++ (0) | 2023.01.12 |
|---|---|
| 완주하지 못한 선수 - 프로그래머스, C++ (1) | 2023.01.11 |
| 올바른 괄호 - 프로그래머스, c++ (0) | 2023.01.10 |
| 같은 숫자는 싫어 - 프로그래머스, c++ (0) | 2023.01.08 |
| 옹알이 (1) - 프로그래머스, c++ (0) | 2023.01.07 |