Posts [프로그래머스] 문자열 내 마음대로 정렬하기 / C++
Post
Cancel

[프로그래머스] 문자열 내 마음대로 정렬하기 / C++


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


  1. 비교 함수 cmp를 만들어, n번째 글자 기준으로 맞게 정렬되었으면 true, 역순이면 false를 리턴해줍니다.

  2. sort 함수로 strings를 정렬할 때, cmp 리턴값이 false이면 비교 대상 두 값의 자리를 바꾸고, true이면 바꾸지 않게 동작합니다.


소스 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

int N;
bool cmp(string a, string b){
    if(a[N] == b[N]){
        return a < b;
    }
    else{
        return a[N] < b[N];
    }
}

vector<string> solution(vector<string> strings, int n) {
    N=n;
    sort(strings.begin(), strings.end(), cmp);
    return strings;
}



This post is licensed under CC BY 4.0 by the author.

[프로그래머스] 나누어 떨어지는 숫자 배열 / C++

[프로그래머스] 시저 암호 / C++

Comments powered by Disqus.