알고리즘
[2019 카카오 개발자 겨울 인턴십] 튜플
슈뢰딩거의 고등어
2022. 4. 17. 14:13
https://programmers.co.kr/learn/courses/30/lessons/64065
코딩테스트 연습 - 튜플
"{{2},{2,1},{2,1,3},{2,1,3,4}}" [2, 1, 3, 4] "{{1,2,3},{2,1},{1,2,4,3},{2}}" [2, 1, 3, 4] "{{4,2,3},{3},{2,3,4,1},{2,3}}" [3, 2, 4, 1]
programmers.co.kr
[풀이]
1. 벡터에 각 원소를 저장한다.
2. 길이 순으로 정렬한다.
3. answer 에 넣은 적이 없다면 answer 에 숫자를 넣는다.
[전체 코드]
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool visit[100000];
vector <vector <int> > v;
bool cmp(vector <int> a, vector <int> b) {
return a.size() < b.size();
}
vector<int> solution(string s) {
vector<int> answer;
bool start = false;
string no = "";
vector <int> tmp;
for(int i=1; i<s.size(); i++) {
string ele = s.substr(i, 2);
if(ele == "}," || ele == "}}") {
start = false;
tmp.push_back(stoi(no));
v.push_back(tmp);
continue;
}
else if(s[i] == '{') {
tmp.clear();
no = "";
}
else if(s[i] == ',') {
tmp.push_back(stoi(no));
no = "";
}
else
no += s[i];
}
sort(v.begin(), v.end(), cmp);
for(auto list : v) {
for(auto ele : list) {
if(visit[ele] == false){
answer.push_back(ele);
visit[ele] = true;
}
}
}
return answer;
}
python 을 사용했더라면 변환 없이 바로 사용이 가능했겠지만, 파이썬 안쓴지가 오래되기도 했고, 코테는 학부시절부터 c++ 로 풀어왔던지라 그냥 c++ 로 작성했다.