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

1 분 소요

1.문제 링크

튜플



2. 풀이 전 계획과 생각

  • 구현



3. 풀이

#include <string>
#include <vector>
#include<algorithm>
#include<iostream>
using namespace std;

bool check[100001];

bool compare(vector<int> &a, vector<int> &b){
    if(a.size()<b.size()) return true;
    else return false;
}

vector<int> solution(string s) {
    s.erase(0,1);
    s.erase(s.size()-1,1);

    vector<vector<int> > v;
    int index_start=0;
    while(1){
        int openIndex = s.find('{',index_start);
        int closeIndex = s.find('}',index_start);
        if(openIndex==-1) break;

        string str = s.substr(openIndex+1,closeIndex-openIndex-1);
        //cout<<str<<endl;
        int index_com = 0;
        vector<int> temp;
        while(1){
            int comindex = str.find(',',index_com);
            if(comindex==-1){
                temp.push_back(stoi(str.substr(index_com)));
                break;
            }
            temp.push_back(stoi(str.substr(index_com,comindex-index_com)));
            index_com = comindex+1;
        }
        //for(int i=0;i<temp.size();i++){cout<<temp[i]<<' ';}
        //cout<<endl;
        v.push_back(temp);

        index_start = closeIndex+1;
    }

    sort(v.begin(), v.end(), compare);

    //for(int i=0;i<v.size();i++) cout<<v[i].size()<<' ';

    vector<int> answer;
    for(int i=0;i<v.size();i++){
        for(int j=0;j<v[i].size();j++){
            if(check[v[i][j]]== false){
                answer.push_back(v[i][j]);
                check[v[i][j]]= true;
                break;
            }
        }
    }

    return answer;
}

{ {2}, {2, 1}, {2, 1, 3}, {2, 1, 3, 4} }가 있다면

  1. 가장 큰 중괄호 제거. { {2}, {2, 1}, {2, 1, 3}, {2, 1, 3, 4} } -> {2}, {2, 1}, {2, 1, 3}, {2, 1, 3, 4}

  2. 각 중괄호를 제거해 str에 저장하기 2 2, 1 2, 1, 3 2, 1, 3, 4

  3. ’,’를 제거해 temp 벡터에 넣기(int형으로 변환)

  4. 각 temp 벡터를 v벡터에 넣기

  5. v벡터를 크기순으로 오름차순

  6. check배열을 이용해 한번 answer 벡터에 삽입된 정수는 true처리하고 false인 것만 삽입.



4. 풀이하면서 고민했던 점

  • 문자열을 전처리하는 방법에 대해 고민함.



5. 문제를 풀고 알게된 개념 및 소감