본문 바로가기

Algorithm/프로그래머스

프로그래머스 튜플 C++

반응형

프로그래머스 : 튜플

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


- 문제

  특정 튜플을 표현하는 집합이 담긴 문자열이 주어지면 튜플을 구하는 문제다.

 


- 풀이

#include <string>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

bool cmp(pair<int,int> &a, pair<int,int> &b){
    // if(a.second == b.second) return a.first > b.first;
    return a.second > b.second;
}

vector<int> solution(string s) {
    vector<int> answer;
    map<int,int> m;
    string temp;
    for(int i = 1; i < s.size()-1; i++){
        if(s[i] != '{' && s[i] != '}' && s[i] != ','){
            temp += s[i];
            if(s[i+1] != ',' && s[i+1] != '}'){
                continue;
            }
            m[stoi(temp)]++;
        }
        temp.clear();
    }
    
    vector<pair<int,int>> vp(m.begin(),m.end());
    sort(vp.begin(),vp.end(),cmp);
    for(auto i : vp){
        answer.push_back(i.first);
    }
    
    return answer;
}

 

 

모든 숫자가 몇 번씩 나왔는지 세고, 가장 많이 나온 숫자부터 result에 하나씩 추가한다.

 

  


- 기억할 것!

 X

반응형