문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요.
s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주 합니다.
| s | return |
|---|---|
| "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에서 변경하고자 했기 때문에 안됐던 것 같다.