GitHubSeob

C++ / 프로그래머스 / 튜플 본문

Programmers/Level 2

C++ / 프로그래머스 / 튜플

GitHubSeob 2023. 7. 16.
문제

 

https://school.programmers.co.kr/learn/courses/30/lessons/64065

 

프로그래머스

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

programmers.co.kr

 

 

문제풀이

 

문제를 대충 봐서인지, 제대로 이해 못한건지 입출력 예와 여러가지 경우의 수가 생각나 쉽게 접근을 못했다.

질문글을 봤더니 이미 완성된 튜플이 있고, 그의 부분집합들이 s로 주어지고, 결과는 숫자의 빈도수 기준으로 내림차순된 숫자들을 나열한 것이었다.

따라서 문자열에서 '{', '}', ',' 만 제외하고 숫자들만 따로 저장하고, 빈도수를 저장하여 정렬하여 return하면 된다.

 

map<string, int>count를 선언하여 key에는 숫자를, value에는 해당 숫자의 빈도수를 저장한다.

isdigit을 이용하여 숫자만 임시 변수 number에 더하고, 숫자가 아닐때 number에 문자열이 있으면 count에 저장한다.

 

반복문이 끝났으면 map을 key가 아닌 value를 기준으로 정렬하기 위해 벡터에 복사하여 정렬한다.

벡터를 정렬하고, stoi를 통해 int으로 변환하여 push_back한다.

 

 

코드
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

bool cmp(pair<string, int>& p1, pair<string, int>& p2) {
    return p1.second > p2.second;
}

vector<int> solution(string s) {
    int idx(0);
    vector<int>answer;
    unordered_map<string, int>count;
    string number("");

    for (idx = 0; idx + 1 < s.size(); ++idx) {
        if (isdigit(s[idx])) {
            number += s[idx];
        }
        else if (!number.empty()) {
            ++count[number];
            number.clear();
        }
    }
    vector<pair<string, int>>tuple(count.begin(), count.end());
    sort(tuple.begin(), tuple.end(), cmp);

    for (idx = 0; idx < tuple.size(); ++idx) {
        answer.push_back(stoi(tuple[idx].first));
    }

    return answer;
}