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

YH J·2023년 6월 5일
0

프로그래머스

목록 보기
114/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/12915

내 풀이

sort할 때 compare 함수를 잘 이용해야 할 문제인거 같아서 만들었다. 숫자n은 전역변수로 넘겨주었다.
인덱스에 해당하는 글자가 같으면 입력된 문자열 전체를 비교하였고 아니면 해당 인덱스의 글자로만 크기를 비교했다.
comp함수 만들 때 <인가 >인가를 잘 생각해서 구현하자. 1번입력과 2번입력중 2번이 큰 경우는 오름차순 1번이 큰 경우는 내림차순
s1 < s2 : 오름차순
s1 > s2 : 내림차순

내 코드

#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int num = 0;
bool cmp(string& s1, string& s2)
{
    if(s1[num] == s2[num])
        return s1 < s2;
    return s1[num] < s2[num];
}
vector<string> solution(vector<string> strings, int n) {
    num = n;
    sort(strings.begin(),strings.end(), cmp);
    return strings;
}

다른 사람의 풀이

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

다른 사람의 풀이 해석

compare에서 삼항연산자를 사용하였다.

profile
게임 개발자 지망생

0개의 댓글