728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/17686
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90
👩💻 코드
#include <string>
#include <vector>
#include <cctype>
#include <set>
#include <algorithm>
using namespace std;
struct File {
string fileName;
string head;
string tail;
int number;
int index;
File(string fileName, int index) : fileName(fileName), index(index){
size_t i = 0;
for (; i < fileName.size(); i++){
if(isdigit(fileName[i])) {
break;
}
}
size_t j = i;
for (; j < fileName.size(); j++){
if(!isdigit(fileName[j])){
break;
}
}
head = fileName.substr(0, i);
number = stoi(fileName.substr(i, j));
tail = fileName.substr(j);
}
};
struct CustomCompare {
bool operator()(const File& a, const File& b) const {
string a_head = a.head;
string b_head = b.head;
transform(a_head.begin(), a_head.end(), a_head.begin(), ::tolower);
transform(b_head.begin(), b_head.end(), b_head.begin(), ::tolower);
if(a_head == b_head){
if(a.number == b.number){
return a.index < b.index;
} else{
return a.number < b.number;
}
} else {
return a_head < b_head;
}
}
};
vector<string> solution(vector<string> files) {
vector<string> answer;
vector<File> fileList;
for(int i=0; i<files.size(); i++){
fileList.emplace_back(files[i], i);
}
sort(fileList.begin(), fileList.end(), CustomCompare());
for(auto file : fileList){
answer.push_back(file.fileName);
}
return answer;
}
📝 풀이
head, number, tail 부분을 나누어 저장하는 File 구조체를 구현했습니다.
fileName과 index는 생성자의 멤버 초기화합니다.
fileName에서 숫자로 시작하는 부분과 끝나는 부분의 인덱스를 찾습니다.
찾은 인덱스를 활용하여 head, number, tail에 알맞게 저장합니다.
원하는 정렬을 수행하기 위해 CustomCompare 구조체를 구현했습니다.
대소문자를 구분하지 않기 위해 head 부분을 모두 소문자로 변경했습니다.
head와 number가 모두 같으면 index를 기준으로 정렬합니다.
head와 같으면 number를 기준으로 정렬합니다.
head가 다르면 head를 기준으로 정렬합니다.
문제에 주어진 files의 정보들을 File 객체로 생성하여 fileList에 추가합니다.
fileList를 CustomCompare를 이용하여 정렬합니다.
최종적으로 정렬된 파일들을 answer에 추가한 후 return 합니다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 2 x n 타일링 (0) | 2024.08.23 |
---|---|
[프로그래머스] 숫자 변환하기 (0) | 2024.08.23 |
[프로그래머스] 오픈채팅방 (0) | 2024.08.20 |
[프로그래머스] 택배상자 (0) | 2024.08.20 |
[프로그래머스] 주차 요금 계산 (0) | 2024.08.19 |