programmers.co.kr/learn/courses/30/lessons/17686

 

코딩테스트 연습 - [3차] 파일명 정렬

파일명 정렬 세 차례의 코딩 테스트와 두 차례의 면접이라는 기나긴 블라인드 공채를 무사히 통과해 카카오에 입사한 무지는 파일 저장소 서버 관리를 맡게 되었다. 저장소 서버에는 프로그램

programmers.co.kr

<풀이>

1. 파일명들을 입력받는다.

2. 주어진 파일들을 정해진 규칙으로 정렬하여 반환한다.

 

<해법>

1. 파일들을 정해진 규칙에 따라 정렬하는 방법

=> 가장 먼저 주어진 파일들을 HEAD, NUMBER, TAIL을 분류해서 새로운 구조체의 형식으로 만듭니다. 이 후, 주어진 규칙에 따라 정렬하는 기준을 만들고 정렬합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
//구조 : 파일 이름(index, head, number)
struct fileName {
    int index;
    string head;
    int number;
};
 
vector<fileName> v;
 
//fileName 구조체 정렬 기준
bool compare(const fileName& f1, const fileName& f2) {
    if (f1.head == f2.head) {
        if (f1.number == f2.number) {
            return f1.index < f2.index;
        }
        else {
            return f1.number < f2.number;
        }
    }
    else {
        return f1.head < f2.head;
    }
}
 
//해당 문자가 숫자인지 판단하는 함수
bool isNumber(char c) {
    if (c >= '0' && c <= '9') {
        return true;
    }
    return false;
}
 
vector<string> solution(vector<string> files) {
    
    vector<string> answer;
 
    //모든 파일 탐색
    for (int i = 0; i < files.size(); i++) {
 
        //1. 소문자 변환
        string fileString = "";
        for (int j = 0; j < files[i].length(); j++) {
            fileString += tolower(files[i][j]);
        }
 
        //HEAD, NUMBER 초기화
        string HEAD = "";
        string NUMBER = "";
        int pointer = 0;
 
        //2-1. HEAD 분할
        while (pointer >= fileString.length()) {
          
            //숫자가 나오면 반복문 종료
            if (isNumber(fileString[pointer])) {
                break;
            }
 
            HEAD += fileString[pointer];
            ++pointer;
        }
 
        //2-2. NUMBER 분할
        while (pointer >= fileString.length()) {
 
            //숫자가 아닌것이 나오면 반복문 종료
            if (!isNumber(fileString[pointer])) {
                break;
            }
 
            NUMBER += fileString[pointer];
            ++pointer;
        }
 
        //구조체 생성
        fileName f;
        f.index = i;
        f.head = HEAD;
        f.number = stoi(NUMBER);
        
        //3. 벡터에 구조체 저장
        v.push_back(f);
    }
 
    //4. 정렬
    sort(v.begin(), v.end(), compare);
 
    //결과 저장
    for (int i = 0; i < v.size(); i++) {
        answer.push_back(files[v[i].index]);
    }
 
    //반환
    return answer;
}

 

문자열과 구현에 대해 알아볼 수 있는 문제였습니다.

+ Recent posts