Programmers : 파일명 정렬

·2023년 5월 5일
0

알고리즘 문제 풀이

목록 보기
125/165
post-thumbnail

풀이요약

구현

풀이상세

  1. File 이라는 구조체를 형성한다. 구조체의 내용물은 다음과 같다.

    • 입력 순서를 보장하는 idx,
    • head
    • number
    • 본래의 문자열
  2. 기존의 문자열을 head와 number로 나눈 후 File 구조체를 생성한다.

  3. File 구조체를 기반으로 정렬을 시도한다.

    • head, number 가 동일하면 idx로 비교를
    • head 가 동일하면 number를
    • 모두 동일하지 않다면 head를 기반으로 정렬한다.
  4. 정렬된 File 구조체 순서를 기반으로, 본래의 문자열들을 정답에 대입한다.

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<string> go(string str) {
    int idx = 0;
    string tmp = "";
    string num = "";
    vector<string> s;
    while(idx != str.size()) {
        if('0'<=str[idx] && str[idx]<='9') {
            num+=str[idx];
        } else {
            if(num!="") break;
            tmp+=tolower(str[idx]);
        }
        idx++;
    }
    s.push_back(tmp);
    s.push_back(to_string(stoi(num)));
    return s;
}

struct File {
    int i;
    string h;
    int n;
    string s;
};

bool cmp(File a, File b) {
    if(a.h == b.h && a.n == b.n) return a.i < b.i;
    else if(a.h == b.h) return a.n < b.n;
    return a.h < b.h;
}

vector<string> solution(vector<string> files) {
    vector<File> tmp;
    vector<string> answer;
    for(int i=0; i<files.size(); i++) {
        vector<string> s = go(files[i]);
        File f;
        f.i = i;
        f.h = s[0];
        f.n = stoi(s[1]);
        f.s = files[i];
        tmp.push_back(f);
    }
    sort(tmp.begin(), tmp.end(), cmp);
    for(File a : tmp) {
        answer.push_back(a.s);
    }
    
    return answer;
}
profile
새로운 것에 관심이 많고, 프로젝트 설계 및 최적화를 좋아합니다.

0개의 댓글