문제 풀이/Programmers 문제 풀이

[Programmers, C++]#Level2_파일 명 정렬, #include <cctype> 헤더, sort(), Predicate 함수

Hardii2 2024. 7. 25. 11:08


#1. 문제

 

프로그래머스

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

programmers.co.kr

 

 


 

#2. 풀이

 

1. cctype 라이브러리

 

[Basic C++] #56_cctype, 대문자+소문자 확인

[Basic C++] #56_cctype, 대문자+소문자 확인 C++의 라이브러리 중 "cctype"에 대해 알아보겠습니다. cctype 헤더가 제공하는 소문자+대문자 판별 함수에 대한 내용입니다. isdigit, isupper, islower, isspace 1. 헤더

webddevys.tistory.com

 

2. HEAD 추출 시, isalpha(c)가 아니라! isdigit(c)으로 확인하자.

  1. 먼저, 파일 정보를 담고 있는 구조체를 선언합니다.
  2. 각 파일 마다 이름, head, number, index 멤버의 정보를 계산합니다. 
  3. 이때, head 추출 시 isalpha(c)로 할 경우, 특수 문자들에 대한 처리가 정상적으로 이루어지지 않아 오류가 발생합니다. 따라서,! isdigit(c)으로 확인합니다.
  4. 마지막으로, sort() 함수를 호출합니다. 이때, 별도로 정의한 Predicate 함수를 통해 그 우선순위를 결정해주어 정렬 작업을 수행합니다.

 


 

#3. 코드

/*
    @링크: https://school.programmers.co.kr/learn/courses/30/lessons/17686
    @문제: 세부 조건을 만족하는 파일 명 정렬 목록 
    @설명
        1. HEAD 추출 시 isalpha(C)가 아니라, !isdigit(C)으로 추출(특수 문자 고려)
        2. NUMBER 추출 시 최대 5글자 까지 검색을 수행하고, 0일 경우를 고려해야 한다.
*/

#include <string>
#include <vector>
#include <algorithm>
#include <cctype>

using namespace std;

struct FileInfo {
    string name;
    string head;
    int number;
    int Index;
};

bool compareFileInfo(const FileInfo& a, const FileInfo& b) {
    if (a.head != b.head) return a.head < b.head;
    if (a.number != b.number) return a.number < b.number;
    return a.Index < b.Index;
}

vector<string> solution(vector<string> files) {
    vector<FileInfo> fileInfos;
    for(int i=0; i<(int)files.size(); ++i)
    {
        string file = files[i];
        FileInfo info;
        info.name = file;
        info.Index = i;

        int cur = 0;
        //@HEAD 추출 (숫자가 나올 때까지)
        while(cur < file.size() && !isdigit(file[cur]))
        {
            info.head += tolower(file[cur++]);
        }

        //@NUMBER 추출 (최대 5자리)
        string tmp = "";
        while(cur < file.size() && isdigit(file[cur]) && tmp.length() < 5)
        {
            tmp += file[cur++];
        }
        info.number = tmp.empty() ? 0 : stoi(tmp);

        fileInfos.push_back(info);
    }

    stable_sort(begin(fileInfos), end(fileInfos), compareFileInfo);

    vector<string> answer;
    for(const auto& info : fileInfos)
    {
        answer.push_back(info.name);
    }

    return answer;
}