본문 바로가기

problem solving

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

#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
bool compare(vector<string> a, vector<string> b) {
    string str1 = "";
    string str2 = "";
    for(int i = 0; i < a[0].length(); i++) {
        str1 += toupper(a[0][i]);
    }
    for(int i = 0; i < b[0].length(); i++) {
        str2 += toupper(b[0][i]);
    }
    
    if(str1.compare(str2) == 0) {
        return stoi(a[1]) < stoi(b[1]);
    }
    return str1.compare(str2) < 0;
}
 
vector<string> solution(vector<string> files) {
    vector<string> answer;
    vector<vector<string>> div_str;
    vector<string> temp;
    int count, index;
    string str;
    for(int i = 0; i < files.size(); i++) {
        temp.clear();
        count = 0, index = 0;
        str = "";
        while(count < 2 && files[i].length() > index) {
            str = str + files[i][index++];
            //HEAD 부분 추출
            if(count == 0 && (files[i][index] - '0'<= 9 && (files[i][index] - '0'>= 0) {
                temp.push_back(str);
                str = "";
                count++;
            //NUMBER 부분 추출
            } else if(count == 1 && (!((files[i][index] - '0'<= 9 && (files[i][index] - '0'>= 0|| str.length() >= 5)) {
                temp.push_back(str);
                str = "";
                count++;
            }
        }
        str = "" + to_string(i);
        //여기서 str은 파일의 위치 
        temp.push_back(str);
        div_str.push_back(temp);
    }
    
    //순서를 유지해야하기 때문에 stable_sort 이용
    stable_sort(div_str.begin(), div_str.end(), compare);    
    
    for(int i = 0; i < div_str.size(); i++) {
        answer.push_back(files[stoi(div_str[i][2])]);
    }
    return answer;
}
cs