리뷰

문자열 내림차순으로 배치하기 프로그래머스 level 1 문제

C++에서 제공하는 퀵소트로 구현된 오름차순 정렬 sort() 함수를 썼다.

#include <algorithm>
void sort(T start, T end, Compare comp)

세번째에 기준 인자, 함수를 줄 수 있다.

내림차순은 greater<자료형>() 오름차순은 less<자료형>()

  • sort(s.begin(), s.end()); // 기본은 오름차순 정렬
  • sort(s.begin(), s.end(), greater<자료형>());
  • sort(s.begin(), s.end(), less<자료형>());

헤더파일을 inlude 하고 greater, less, plus minus 를 사용할 수 있다.

코드

#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;


string solution(string s) {

    sort(s.begin(), s.end(), greater<char>());
    return s;

}

int main(void)
{
    string input = "Zbcdefg";    
    string answer = "";

    answer = solution(input);

    // string 클래스를 char* 형태로 변환할 때는 c_str() 
    printf("%s", answer.c_str());
    // 출력내용 : gfedcbZ 

    return 0;
}
728x90

'알고리즘 > 프로그래머스' 카테고리의 다른 글

문자열 다루기 기본  (0) 2020.07.17
다리를 지나는 트럭  (0) 2020.07.16
소수찾기 (에라토스테네스의 체)  (0) 2020.07.16
쇠막대기  (0) 2020.07.15
H-index  (0) 2020.06.30

+ Recent posts