• Home
  • About
    • Zzu-h photo

      Zzu-h

      주니어 Android 개발자입니다.

    • Learn More
    • Email
    • Instagram
    • Tistory
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

[프로그래머스] [3차] 파일명 정렬

20 May 2022

Reading time ~1 minute

[3차] 파일명 정렬

링크: [3차]-파일명-정렬


각 파일명을 받으며 헤더와 넘버를 구분하여 따로 저장한다.
그 후 주어진 정렬 순서대로 정렬을 수행 후 그 값들을 출력한다.


  • 정답 코드
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

vector<pair<int, pair<string, int>>> list;

bool comp(pair<int, pair<string, int>> &a, pair<int, pair<string, int>> &b){
    if(a.second.first == b.second.first){
        if(a.second.second == b.second.second)
            return a.first < b.first;
        return a.second.second < b.second.second;
    }
    return a.second.first < b.second.first;
}

bool isNumber(char c){
    if(c >= '0'&& c <= '9') return true;
    else return false;
}

vector<string> solution(vector<string> files) {
    vector<string> answer;
    int size = files.size();
    
    for(int i = 0; i< size; i++){
        string str = files[i];
        string head = "";
        string number = "";
        int idx = 0;
        for(; idx < str.size(); idx++){
            if(isNumber(str[idx])) break;
            head.push_back(str[idx]);
        }

        for(; idx < str.size(); idx++){
            if(isNumber(str[idx])) number.push_back(str[idx]);
            else break;
        }
        transform(head.begin(), head.end(), head.begin(), ::tolower);
        
        while(number[0] == '0')
            number.erase(0,1);
        list.push_back({i, {head, atoi(number.c_str())}});

    }
    sort(list.begin(),list.end(), comp);
    
    for(int i = 0; i< size; i++)
        answer.push_back(files[list[i].first]);
    return answer;
}


PS프로그래머스LV2문자열 Share Tweet +1