작심 24/7

[프로그래머스] 파일명 정렬 2018 KAKAO BLIND RECRUITMENT 본문

프로그래머스/Level 2

[프로그래머스] 파일명 정렬 2018 KAKAO BLIND RECRUITMENT

모닝수박 2020. 5. 23. 03:10
 

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

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

programmers.co.kr

level 2 길래 가벼운 마음으로 시작했다가 무거운 마음으로 겨우 끝냈다.

문제의 조건을 꼼꼼히 읽어봤으면 더 빨리 끝낼 수 있었을까..?

 

1. HEAD를 비교할 때 소문자로 바꾸어 준다

 

2. NUMBER는 최대 5개의 숫자로만 이루어져 있다

 

3. NUMBER의 앞부분에 0이 있으면 일단 size를 체크해 뒀다가 나중에 출력 시 앞에 더해준다

 

4. HEAD, NUMBER, TAIL의 구분을 명확히 해야 한다

ex) aBc009dd78 -> HEAD=aBc, NUMBER=009, TAIL=dd78

 

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

using namespace std;

class Standard {
public:
	string head, tail;
	int number, index, number_size;

	Standard(string head, int number, int index, string tail, int number_size) {
		this->head = head;
		this->number = number;
		this->index = index;
		this->tail = tail;
		this->number_size = number_size;
	}
};

bool compare(Standard a, Standard b) {
	string A = a.head, B = b.head;
	std::transform(A.begin(), A.end(), A.begin(), ::tolower); //소문자로 바꿔주는 함수
	std::transform(B.begin(), B.end(), B.begin(), ::tolower);
	if (A == B) { //HEAD가 같을 경우 NUM을 기준으로 정렬
		if (a.number == b.number) return a.index < b.index; //NUM도 같을 경우 index 기준으로 정렬
		else return a.number < b.number;
	}
	else return A < B;
}

vector<string> solution(vector<string> files) {
	vector<string> answer;
	vector<Standard> v;

	for (int i = 0; i < files.size(); i++) {
		string HEAD, NUM, TAIL;
		int NUMBER = 0, HEAD_cnt = 0, NUMBER_cnt = 0, TAIL_cnt = 0;

		for (int j = 0; j < files[i].size(); j++) {
			if (NUMBER_cnt == 0 && (files[i][j] == '.' || files[i][j] == '-' || files[i][j] == ' ' 
           		 || (files[i][j] >= 'a'&&files[i][j] <= 'z') || (files[i][j] >= 'A'&&files[i][j] <= 'Z'))) { //숫자가 나오기 전까진 HEAD
				HEAD += files[i][j];
				HEAD_cnt++;
			}
			else if (TAIL_cnt == 0 && NUMBER_cnt < 5 && HEAD_cnt != 0 && files[i][j] >= 48 && files[i][j] <= 57) { //숫자가 처음 나올 때부터 NUMBER. 최대 5개까지의 숫자만 취급한다
				NUM += files[i][j];
				NUMBER_cnt++;
			}
			else if (HEAD_cnt != 0 && NUMBER_cnt != 0) { //이후는 무조건 TAIL
				TAIL += files[i][j];
				TAIL_cnt++;
			}
		}

		int ten = 1;
		for (int n = NUMBER_cnt - 1; n >= 0; n--) { //string형 NUM를 int형 NUMBER로 바꿔줌
			NUMBER += ten*(NUM[n] - 48);
			ten *= 10;
		}
		v.push_back(Standard(HEAD, NUMBER, i, TAIL, NUMBER_cnt));
	}

	sort(v.begin(), v.end(), compare);

	for (int i = 0; i < v.size(); i++) {
		string Number, temp;

		temp = to_string(v[i].number);
		if (temp.size() < v[i].number_size) { //빈 칸이 있으면 그만큼 앞에서부터 0으로 채워준다
			for (int j = 0; j < v[i].number_size - temp.size(); j++) {
				Number += '0';
			}
		}
		Number += temp;

		answer.push_back(v[i].head + Number + v[i].tail);
	}

	return answer;
}
Comments