hyunjin

[level 1] 문자열 내 맘대로 정렬하기 , string compare, pair, sort 본문

알고리즘 연습/프로그래머스

[level 1] 문자열 내 맘대로 정렬하기 , string compare, pair, sort

_h.j 2020. 7. 14. 22:36
728x90

https://programmers.co.kr/learn/courses/30/lessons/12915?language=cpp

level1>연습문제>문자열 내 마음대로 정렬하기

 

첫 번째 방법

#include <string>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;
bool compare(pair <string, char> a, pair <string, char> b){
    if(a.second == b.second ) return (a.first).compare(b.first)>0 ? false: true;
    return a.second < b.second;
}

vector<string> solution(vector<string> strings, int n) {
    vector<string> answer;
    vector<pair<string,char>> temp;
    for(string elem : strings){
        temp.push_back( make_pair(elem , elem[n]) );
    }
    
    sort(temp.begin(),temp.end(),compare);
    for(int i = 0 ; i < temp.size(); i++)
        answer.push_back(temp[i].first);
    return answer;
}

음 좀 더 간단하게 줄일 수 있는 방법을 다른 사람 풀이에서 찾았다.

문제 핵심 포인트인 sort compare 흐름은 같지만 temp를 사용하지 않고 바로 비교 할 수 있다.

 

두 번째 풀이

#include <string>
#include <vector>
#include <algorithm>
#include <utility>

using namespace std;

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) {
    vector<string> answer;
    i = n;
    answer.assign(strings.begin(), strings.end());
    sort(answer.begin(),answer.end(),compare);
    return answer;
}

string 자체 비교하는 것을 compare를 사용해야하는 줄 알았는데 부등호로도 바로 가능하다.

 

 

 

 

 

728x90