프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 과정
이 문제는 구조체 벡터를 만들고, 그 벡터를 구조체의 조건에 따라
정렬 함수를 만드는 게 중요하다.
head와 number 부분은 중요하지만, tail부분은 index로 대체할 수 있다.
head와 number 부분을 찾는 방법은 숫자가 나올 때 idx벡터에 넣고,
0부터 idx[0]까지는 head, idx[0]부터 idx[0] + idx.size()까지는 number이다.
그 다음 구조체를 만들어 벡터에 넣어주고, 정렬을 해주면 된다.
head가 같고, number가 같을 경우 index를 기준으로 정렬하고
number가 다를 경우 number를 기준으로 정렬하고
head가 다를 경우 head를 기준으로 정렬하면 된다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct fileName {
int index;
string head;
int number;
};
vector<fileName> v;
bool cmp(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;
}
vector<string> solution(vector<string> files) {
vector<string> answer;
for(int i = 0; i < files.size(); i++){
vector<int> idx;
for(int j = 0; j < files[i].size(); j++){
if('0' <= files[i][j] && files[i][j] <= '9'){
idx.push_back(j);
}
}
string head = "";
for(int j = 0; j < idx[0]; j++){
head += tolower(files[i][j]);
}
string number = files[i].substr(idx[0], idx.size());
fileName f;
f.index = i;
f.head = head;
f.number = stoi(number);
v.push_back(f);
}
sort(v.begin(), v.end(), cmp);
for(int i = 0; i < v.size(); i++){
answer.push_back(files[v[i].index]);
}
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level2] 땅따먹기 c++ (0) | 2022.10.21 |
---|---|
[프로그래머스][Level2] 기능 개발 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 멀쩡한 사각형 c++ (0) | 2022.10.21 |
[프로그래머스][Level2] 거리두기 확인하기 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] N개의 최소공배수 c++ (0) | 2022.10.20 |