KDT Unity 2주차~4주차
2023-12-01 TIL
알고리즘 문제
오늘의 알고리즘 문제 : 문자열 내림차순으로 배치하기
문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요. s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다.
1
2
3
4
5
6
public class Solution {
public string solution(string s) {
string answer = "";
return answer;
}
}
해결
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Diagnostics;
using System.Linq;
public class Solution {
public string solution(string s) {
string answer = "";
char[] ans = s.ToCharArray();
System.Array.Sort(ans);
System.Array.Reverse(ans);
answer = new string(ans);
return answer;
}
}
char[] ans = s.ToCharArray();을 사용하여 문자열을 문자배열로 만듭니다. System.Array.Sort(ans); 작은 순으로 정렬합니다. System.Array.Reverse(ans); 해당 배열을 뒤집습니다. answer = new string(ans); string으로 합치고 리턴합니다.
This post is licensed under CC BY 4.0 by the author.
