알고리즘 & 자료구조/코딩테스트

[프로그래머스]문자열 내림차순으로 배치하기(C++)

인디아나쥰이 2021. 2. 9. 20:05

문제 설명

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

 

제한 사항

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

입출력 예

s                                                                                                       return

Zbcdefg gfedcbZ

 

 

sort() 를 이용하면 간단히 해결가능

 

sort 내림차순 정리한 내용 => junecode.tistory.com/67

 

 

 

 

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

using namespace std;

//첫 번째 방법
bool comp(char a, char b)
{
    return a > b;
}

string solution(string s) {
    string answer = "";
    sort(s.begin(), s.end(), comp);
    answer = s;
    return answer;
}


//두 번째 방법
string solution2(string s) {
    string answer = "";
    sort(s.begin(), s.end(), greater<char>());
    answer = s;
    return answer;
}


int main(void)
{
    string s;
    cin >> s;
    cout << solution(s);

}
728x90
반응형