알고리즘/PS - 프로그래머스
[프로그래머스 - C++] 튜플
excited-hyun
2021. 7. 9. 16:33
반응형
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
풀이
이 문제를 읽고 우선 원소의 개수 순서대로 정렬해야할 필요가 있다는 생각을 했다.
- 벡터에 {} 단위로 잘라서 길이와 해당 string을 저장한다.
- 이때 사용하는 벡터는 vector<pair<int, string>> save 의 형태이다. (길이와 해당 문자열 저장해야하므로)
- 벡터를 오름차순 정렬한다.
- 벡터의 string을 순서대로 삭제하면서 읽고 아직 answer 벡터에 저장되지 않은 숫자 발견시 push_back해준다.
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
vector<int> solution(string s) {
vector<int> answer;
string temp;
vector<pair<int, string>> save;
int num;
for(int i=0; i<s.length(); i++){
if(s[i] == '{'){
temp = "";
}
else if(s[i] == '}'){
if (temp.length()!=0){
save.push_back(make_pair(temp.length(), temp));
temp="";
}
}
else{
temp = temp+s[i];
}
}
sort(save.begin(), save.end());
for(int i=0; i<save.size(); i++){
int j=0;
while(j < save[i].first){
sscanf(save[i].second.c_str(),"%d", &num); //숫자 하나씩
save[i].second.erase(0, to_string(num).length()+1); //그 숫자 지움
j+=to_string(num).length()+1;
vector<int>::iterator it;
it = find(answer.begin(), answer.end(), num);
if(it==answer.end()) //아직 벡터에 없을 때만 추가
answer.push_back(num);
}
}
return answer;
}
728x90
반응형