프로그래머스 - [3차] 방금그곡
구현 문제긴한데, 코너케이스 때문에 좀 애먹었다.
이런 유형의 카카오 문제들은
1. 문자열 파싱을 잘 할 수 있는지
2. 주어진 조건을 구현할 수 있는지
3. 예외 케이스를 생각해낼 수 있는지 (구현할 때부터 최대한 예외케이스가 없도록 잘 짜는게 핵심인 것 같다)
"DF", ["6:20,6:50,TEST,DDF"] -> "TEST"
해당 케이스를 None으로 출력해서 #TC 12를 통과하지 못했었다.
코드는 아래와 같다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void parse2(string target, vector<string> &result)
{
int idx = 0;
for(int i=0;i<target.size();i++) {
if(target[i] == '#') {
result[idx - 1].push_back('#');
} else {
string tmp;
tmp.push_back(target[i]);
result.push_back(tmp);
idx++;
}
}
}
void parse(string target, vector<string> &result)
{
string tmp;
int j = 0;
while(1) {
if(j >= target.size()) {
result.push_back(tmp);
break;
}
if(target[j] == ',') {
result.push_back(tmp);
tmp = "";
} else
tmp.push_back(target[j]);
j++;
}
}
void get_time(string start, string end, int &time, int &start_time)
{
string hst; hst.push_back(start[0]); hst.push_back(start[1]);
string het; het.push_back(end[0]); het.push_back(end[1]);
string mst; mst.push_back(start[3]); mst.push_back(start[4]);
string met; met.push_back(end[3]); met.push_back(end[4]);
int hour = stoi(het) - stoi(hst);
int min = stoi(met) - stoi(mst);
time = hour * 60 + min;
start_time = stoi(hst) * 60 + stoi(mst);
}
void fit(vector<string> &music, int time)
{
if(music.size() == time)
return;
if(music.size() > time) {
while(1) {
if(music.size() == time)
break;
music.pop_back();
}
return;
}
int idx = 0;
while(1) {
if(music.size() == time)
break;
music.push_back(music[idx]);
idx++;
}
}
bool comp(const pair<int, pair<int, string>> &a, const pair<int, pair<int, string>> &b)
{
if(a.first == b.first)
return a.second.first < b.second.first;
return a.first > b.first;
}
string solution(string m, vector<string> musicinfos) {
string answer = "";
vector<string> parse_m;
parse2(m, parse_m);
string m_fin = "";
for(int i=0;i<parse_m.size();i++)
m_fin += parse_m[i];
vector<pair<int, pair<int, string>>> candidate;
for(int i=0;i<musicinfos.size();i++) {
vector<string> result;
vector<string> music;
parse(musicinfos[i], result);
parse2(result[3], music);
int time, start_time;
get_time(result[0], result[1], time, start_time);
if(time < parse_m.size())
continue;
fit(music, time);
int k = 0;
for(int j=0;j<music.size();j++) {
if(music[j].compare(parse_m[k]) == 0)
k++;
else
k = music[j].compare(parse_m[0]) ? 0 : 1;
if(k == parse_m.size())
break;
}
if(k == parse_m.size())
candidate.push_back( { time, { start_time, result[2] }} );
}
if(candidate.size() == 0) {
return "(None)";
} else {
sort(candidate.begin(), candidate.end(), comp);
return candidate[0].second.second;
}
}
Author And Source
이 문제에 관하여(프로그래머스 - [3차] 방금그곡), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@gkak1121/프로그래머스-3차-방금그곡저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)