C# 프로그래머스 [Level 1] _문자열 내 마음대로 정렬하기
2020. 6. 17. 15:52ㆍ프로그래머스 알고리즘/코딩 테스트 문제
반응형
C# 프로그래머스 [Level 1] _문자열 내 마음대로 정렬하기

출제 링크 : programmers.co.kr/learn/courses/30/lessons/12915
코딩테스트 연습 - 문자열 내 마음대로 정렬하기
문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1�
programmers.co.kr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Solution | |
{ | |
// https://programmers.co.kr/learn/courses/30/lessons/12915 | |
// 조건 | |
// - strings는 길이 1 이상, 50이하인 배열입니다. | |
// - strings의 원소는 소문자 알파벳으로 이루어져 있습니다. (대문자로 치환) | |
// - strings의 원소는 길이 1 이상, 100이하인 문자열입니다. | |
// - 모든 strings의 원소의 길이는 n보다 큽니다. | |
// - 인덱스 1의 문자가 같은 문자열이 여럿 일 경우, 사전순으로 앞선 문자열이 앞쪽에 위치합니다. | |
public string[] solution(string[] strings, int n) | |
{ | |
string[] answer = new string[] { }; | |
int compareNum; | |
int equalsNum; | |
string tmp; | |
for (int i = 0; i < strings.Length; i++) | |
{ | |
for (int j = i + 1; j < strings.Length; j++) | |
{ | |
compareNum = string.Compare(strings[i], n, strings[j], n, 1); | |
switch (compareNum) | |
{ | |
// 비교 대상이 같거나 Legth가 0일 경우 | |
case 0: | |
// CompareTo | |
// - 배열 전체를 비교함 | |
// -1 : 정렬 된 경우 | |
// 1 : 비교 대상이 클 경우 | |
equalsNum = strings[i].CompareTo(strings[j]); | |
if (equalsNum > 0) | |
{ | |
tmp = strings[j]; | |
strings[j] = strings[i]; | |
strings[i] = tmp; | |
} | |
break; | |
case 1: | |
tmp = strings[j]; | |
strings[j] = strings[i]; | |
strings[i] = tmp; | |
break; | |
} | |
} | |
} | |
answer = strings; | |
return answer; | |
} | |
public static void Main() | |
{ | |
string[] strings = { "sun", "bed","car" }; | |
int n = 1; | |
Solution solution = new Solution(); | |
string[] temp = solution.solution(strings, n); | |
foreach (var i in temp) | |
{ | |
Console.WriteLine(i); | |
} | |
} | |
} |
반응형