bdfgdfg

[레벨1] 문자열 내마음대로 정렬하기 본문

코딩테스트/프로그래머스

[레벨1] 문자열 내마음대로 정렬하기

marmelo12 2021. 9. 5. 14:46
반응형
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

struct Compare // 함수 객체
{
    bool operator()(const pair<string, char>& lhs, pair<string, char>& rhs)
    {
        if (lhs.second == rhs.second)
            return lhs.first < rhs.first;
        else
            return lhs.second < rhs.second;
    }
};

vector<string> solution(vector<string> strings, int n) {
    vector<string> answer;

    const int LEN = strings.size();
    vector<pair<string, char> > data;
    data.reserve(LEN);
    for (int i = 0; i < LEN; ++i)
    {
        data.push_back(pair<string, char>(strings[i], strings[i][n]));
    }

    sort(data.begin(), data.end(), Compare());
    for (int i = 0; i < LEN; ++i)
        answer.push_back(data[i].first);
    return answer;
}

나는 함수 객체를 따로 만들어서 sort에 정렬방법을 건네주었다.

 

n으로 넘겨진 인덱스를 기준으로 정렬을 진행하기에 second(char)가 같다면 first를 기준으로 정렬. 그게 아니라면 문자를 기준으로 정렬.

 

다른 사람의 풀이를 보니 매우 간단한 정렬방법이 존재했는데.

int i;

bool compare (string a, string b) {
    return a[i] == b[i] ? a < b : a[i] < b[i];
}

vector<string> solution(vector<string> strings, int n) {
    i = n;
    sort (strings.begin(), strings.end(), compare);
    return strings;

이 사람은 함수를 바로 건네주었고, string을 그대로 받은 다음. 

함수의 인자 n값을 i에 대입해 정렬 함수를 만들었다. -> 기발한 방식!

 

 

반응형
Comments