[C언어] 문자열 내림차순으로 배치하기

tnrms08·2022년 5월 8일
0

프로그래머스

목록 보기
9/21

문제 설명

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

제한 사항

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

입출력 예

sreturn
"Zbcdefg""gfedcbZ"

코드 구현

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>		//strlen() : 문자열의 길이 구하기

char* solution(const char* s) {
    char* answer = (char*)malloc(strlen(s)+1);
    
    strcpy(answer,s);	//answer에 s를 복사(문자열 복사)
    
    for(int i=0;i<strlen(s);i++){
        for(int j=i+1;j<strlen(s);j++){
        	//answer[i]보다 큰 문자가 있는 경우 바꾸기
            if(answer[i]<answer[j]){
                char temp=answer[i];
                answer[i]=answer[j];
                answer[j]=temp;
            }
        }
    }
    return answer;
}

s를 직접적으로 변경할 수 없기 때문에 answer에 s를 복사하여 answer을 변경시켰다.

다른 사람의 코드

원래 c언어에 내장되어 있는 qsort를 사용하려 풀어보려 했는데 결과가 나오지 않았기에 다른 사람의 코드를 참고하였다.
아래는 다른 사람의 코드를 가져 온 것이다.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int compare(const void *a, const void *b)
{
    return -(strcmp((char *)a, (char *) b));
};

char* solution(const char* s) {
    char* answer = (char*)malloc(100000);

    char temp[strlen(s)];
    strcpy(temp, s);
    qsort(temp, strlen(s), sizeof(char), compare);

    strcpy(answer, temp);

    return answer;
}

코드 변형

위의 코드를 보고 좀 더 간단히 할 수 있을 것 같다는 생각이 들어서 약간 변형을 시도하였다.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

int compare(const void *a, const void *b)
{
	//내림차순이기 때문에 '-'를 붙여서 반환
    //(a와 b의 순서 변경도 가능)
    return -(strcmp((char *)a, (char *) b));
};

char* solution(const char* s) {
    char* answer = (char*)malloc(strlen(s));
    
    strcpy(answer, s);
    qsort(answer, strlen(s), sizeof(char), compare);

    return answer;
}

결국 이전에는 strcpy를 진행하지 않고 s에서 변경하고자 했기 때문에 안됐던 것 같다.

0개의 댓글