문제 링크 https://programmers.co.kr/learn/courses/30/lessons/12917

문제

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

제한 조건

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

풀이 과정

문자열도 char형이 여러개 이어진 것이기 때문에 sort를 할 수 있다.
rbegin()과 rend()는 내림차순을 한다는 것이다.

풀이1

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

using namespace std;

string solution(string s) {
    string answer = "";
    sort(s.rbegin(), s.rend());
    answer = s;
    return answer;
}

풀이2

#include <string>
#include <vector>

using namespace std;

string solution(string s) {
    string answer = "";
    // sort 내림차순 구현
    for(int i = 0; i < s.size(); i++){
        for(int j = 0; j < s.size(); j++){
            if(s[i] > s[j]){
                int temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
        }
    }
    answer = s;
    return answer;
}

댓글남기기