문제풀이(Problem Solving)

프로그래머스, 파일명 정렬, C++ [CPP] ★★★★★

게임이 더 좋아 2022. 9. 15. 16:38
반응형
728x170

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

어렵지 않다.

다만 까다로울 수 있다. 특히 number랑 head를 분리할 때 신경써주어야 한다.

 

 


#맞은 풀이

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct File{
    string head = "";
    string number = "";
    string totalName = "";
    int idx = -1;
};


    bool cmp (const File &a, const File &b){
        string head1 ="";
        string head2 ="";
        
        int number1 = -1;
        int number2 = -1;
        for(char c : a.head){
            head1 += tolower(c);
        }
        for(char c : b.head){
            head2 += tolower(c);
        }

        if(head1 == head2){
            number1 = stoi(a.number);
            number2 = stoi(b.number);
            if(number1 == number2){
                return a.idx < b.idx;
            }
            return number1 < number2;
        }
        return head1 < head2;
    }

vector<string> solution(vector<string> files) {
    vector<string> answer;
    vector<File> ff;
    int idx = 1;
    for(auto f : files){
        File x;
        x.idx = idx++;
        bool head = false;
        bool number = false;
        int numIdx = 0;
        for(int i = 0; i<f.size(); i++){
            if(head == false){
                if(isdigit(f[i])){
                    x.head = f.substr(0,i);
                    head = true;
                    numIdx = i;
                    continue;
                }
            }else if(number == false && head == true){
                //숫자가 아니거나 5개 초과하는 숫자를 가질수 없음
                if(!isdigit(f[i]) || i - numIdx + 1 >= 5){
                    x.number = f.substr(numIdx, i-numIdx+1);
                    number = true;
                    break;
                }
            }
        }
        //만약 해당 숫자로 끝나서 숫자가 아닌 문자를 만나지 못해서 끝나면
        if(!number && head){
            x.number = f.substr(numIdx);
        }
        x.totalName = f;
        ff.push_back(x);
    }
    
    sort(ff.begin(), ff.end(), cmp);
    
    for(auto f : ff){
        answer.push_back(f.totalName);
    }
    
    return answer;
}
반응형
그리드형