[프로그래머스]파일명 정렬

GomHyeok·2022년 3월 27일
0
post-thumbnail

📒활용개념

  1. sort, stabl_sort
  2. string의 substr와 transform(위와 동일한 페이지 설명)

Sorting과 String의 함수들을 알고 있었다면 쉽게 풀 수 있었던 문제지만, 모른다면 정말 어려운 문제

📌문제설명

다음과 같이 구성되어 있는 파일명을 조건에 맞게 정렬하여라.
파일명 = Head(문자) + Number(숫자) + Tail(문자, 숫자, NULL)
조건

  • 우선 Head를 기준으로 사전순으로 정렬. 이 때, 대소문자는 구분하지 않는다.
  • 파일명이 대소문자 차이 외에 같을 경우 Number를 기준으로 오름차순으로 정렬한다.
  • Head와 Number모두 같을 경우 입력된 순서를 유지한다.

ex)
input -> ["img12.png", "img10.png", "img02.png", "img1.png", "IMG01.GIF", "img2.JPG"]
output -> ["img1.png", "IMG01.GIF", "img02.png", "img2.JPG", "img10.png", "img12.png"]

📌구현

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int find_num(string st){					//첫 번째 Number자리를 찾는 함수
    int i;
    for(i=0; i<st.size(); i++){
        if(st[i]>='0'&&st[i]<='9'){
            break;
        }
    }    
    return i;
}

int getNumber (string st){					//string에서 Number만 추출한다.
    return stoi(st.substr(find_num(st)));	//stoi는 string의 Number의 첫 번째 자리가 필요하다.
}

string getHead(string st){					//Head를 찾는 함수
    int start=find_num(st);		
    string result;
    result=st.substr(0, start);				//처음부터 Number를 시작하기 전 index까지 저장.
    return result;
}

bool compNum (string a, string b){			//sort를 위한 Number 비교 함수
    return getNumber(a)<getNumber(b);
}

bool compHead(string a, string b){			//sort를 위한 Head 비교 함수
    string first;
    string last;
    first = getHead(a);
    last = getHead(b);
    transform(first.begin(), first.end(), first.begin(), ::tolower);//모든 string 소문자로 전환.
    transform(last.begin(), last.end(), last.begin(), ::tolower);
        
    return first < last ;
}

vector<string> solution(vector<string> files) {
    vector<string> answer;
    
    //stable_sort로 기존의 정렬 유지.
    stable_sort(files.begin(),files.end(),compNum);		//Number기준 정렬.
    stable_sort(files.begin(),files.end(),compHead);	//Head기준 정렬.    
    return files;
}

📌주의점

  • Sorting을 어떤 기준으로 먼저 할 것인가를 생각해야한다. 문제에서는 Head가 기준 1이지만 구현을 할 때는 Number를 기준으로 먼저 Sorting을 해야 Head를 기준 1로 유지할 수 있다.
  • 미리 구현되어있는 함수를 얼마나 알고 있고, 적절하게 활용할 수 있는가.
profile
github : https://github.com/GomHyeok/

0개의 댓글