01
06

문제

문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.

제한 사항

str은 길이 1 이상인 문자열입니다.

 

코드

더보기
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool cmp(char a, char b)
{
    if (a == b)
        return false;
    
    return int(a) > int (b);
}

string solution(string s) {
    string answer = "";
    
    if (s.size() < 1)
    {
        return "";
    }
    
    sort(s.begin(), s.end(), cmp);
    
    answer = s;
    
    return answer;
}

 

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

using namespace std;

string solution(string s) {
    string answer = "";
    
    if (s.size() < 1)
    {
        return "";
    }
    
    sort(s.begin(), s.end(), greater<>());
    
    answer = s;
    
    return answer;
}

코드 해설

문자열을 내림차순으로 정렬하는 문제이다. 여기서 두가지 방식을 사용했다.

첫 코드는 먼저 조건함수를 만들어서, sort로 실행한 것이다.

두번재 코드는 greater<>()를 사용해서 내림차순으로 정렬한 것이다.

 

두번째 코드가 기억이 안나서 첫번째 만들고나서, 부랴부랴 실행했다. ㅎㅎ..

COMMENT