Level 2. [3차] 파일명 정렬
비교에는 HEAD와 NUMBER만 사용하고, TAIL의 조건인 순서 유지는 stable_sort() 함수로 정렬하면 된다.
parse 람다 함수에서 알파벳을 소문자로 만든 HEAD와 NUMBER를 파싱하고 조건대로 정렬해 해결했다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
vector<string> solution(vector<string> files)
{
auto parse = [](const string& s) -> pair<string, int>
{
pair<string, int> pr;
auto it = find_if(s.begin(), s.end(), ::isdigit);
pr.first = string(s.begin(), it);
transform(pr.first.begin(), pr.first.end(), pr.first.begin(), ::tolower);
auto it2 = find_if_not(it, s.end(), ::isdigit);
pr.second = stoi(string(it, it2));
return pr;
};
stable_sort(files.begin(), files.end(), [&parse](const string& a, const string& b)
{
pair<string, int> prA = parse(a), prB = parse(b);
if (prA.first == prB.first)
return prA.second < prB.second;
else
return prA.first < prB.first;
});
return files;
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 1. 공원 산책 (0) | 2023.04.18 |
---|---|
Level 1. 달리기 경주 (0) | 2023.04.17 |
Level 2. 괄호 회전하기 (0) | 2023.04.15 |
Level 2. 가장 큰 수 (0) | 2023.04.14 |
Level 2. 카펫 (0) | 2023.04.13 |