프로그래머스 - 튜플

well-life-gm·2021년 11월 17일
0

프로그래머스

목록 보기
62/125

프로그래머스 - 튜플

주어진 문자열에서 { , 등 특수문자 사이의 숫자만 파싱할 수 있다면 쉬운 문제이다.

숫자가 등장하는 횟수가 가장 많은 숫자부터 적은 횟수를 결과 값으로 반환해주면 된다.

이를 위해 map을 이용해 주어진 문자열에서 숫자(Key)가 등장할 때마다 해당 Value 값을 1씩 증가시켜 줬으며, 이를 벡터에 담아서 Sort해줬다.




코드는 아래와 같다.

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

using namespace std;

bool comp(const pair<int, int> &a, const pair<int, int> &b)
{
    return a.second > b.second;
}
vector<int> solution(string s) {
    string tmp = "";
    map<int, int> m;
    for(int i=0;i<s.size();i++) {
        if(isdigit(s[i])) 
            tmp += s[i];
        else {
            if(tmp.size() == 0) 
                continue;
            m[stoi(tmp)]++;
            tmp = "";
        }
    }

    vector<pair<int, int>> ans(m.begin(), m.end());
    sort(ans.begin(), ans.end(), comp);
    vector<int> answer(m.size(), 0);
    for(int i=0;i<ans.size();i++) 
        answer[i] = ans[i].first;
    
    return answer;
}
profile
내가 보려고 만든 블로그

0개의 댓글