[프로그래머스] 튜플- C++

level 2

Posted by dongjune on December 21, 2020

문제

프로그래머스 튜플

풀이

문제에서 ((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)를 나타냅니다.
자세히 보시면 가장 많이 나오는 숫자 순으로 정렬하면 되는 것을 알 수 있습니다. 2가 4개 나오니까 2를 먼저 그 다음 1이 3개니까 1, 이런 식으로 튜플 (2, 1, 3, 4) 를 찾을 수 있습니다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

vector<int> solution(string s) {
    vector<int> answer;
    
    // 숫자의 개수 세기
    int count[100001]={0};
    
    string temp="";
    // 문자열을 돌며 나오는 수들의 개수를 세기
    for(auto ch : s){
        if(ch-'0'>=0 && ch-'0'<=9){
            temp=temp+ch;
        }else{
            if(temp.length()){
                count[stoi(temp)]++;
                temp="";
            }
        }
    }
    
    vector<pair<int,int>> v;
    for(int i=1;i<=100000;i++){
        if(count[i]){
            v.push_back({count[i],i});
        }
    }
    // 가장 많이 나온 순으로 오름차순 후 뒤집기
    sort(v.begin(),v.end());
    reverse(v.begin(),v.end());
    
    for(auto el:v){
        cout<<el.second<<'\n';
        answer.push_back(el.second);
    }
    return answer;
}