프로그래머스_C#/Level_1
[프로그래머스 C#] 문자열 내림차순으로 배치하기
최애뎡
2021. 8. 31. 00:10
728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/12917
코딩테스트 연습 - 문자열 내림차순으로 배치하기
문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요. s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로
programmers.co.kr
using System;
public class Solution {
public string solution(string s) {
string answer = "";
char[] chr_temp = s.ToCharArray();
Array.Sort(chr_temp);
Array.Reverse(chr_temp);
answer = new string(chr_temp);
return answer;
}
}
Linq를 사용한다면
using System.Linq;
public class Solution {
public string solution(string s) {
string answer = "";
answer = new string(s.OrderByDescending(x => x).ToArray());
return answer;
}
}
이렇게도 할 수 있긴 하나 수행 속도는 많이 느려짐
* string을 OrderBy를 사용해서 정렬할 때 굳이 ToCharArray()는 거칠 필요가 없다.
https://docs.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.orderbydescending?view=net-5.0
Enumerable.OrderByDescending 메서드 (System.Linq)
시퀀스의 요소를 내림차순으로 정렬합니다.Sorts the elements of a sequence in descending order.
docs.microsoft.com
반응형