https://school.programmers.co.kr/learn/courses/30/lessons/12915
문자열로 구성된 리스트 strings
와, 정수 n
이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings
가 ["sun", "bed", "car"]이고 n
이 1이면 각 단어의 인덱스 1의 문자 "u", "e", "a"로 strings를 정렬합니다.
strings는 길이 1 이상, 50이하인 배열입니다.
strings의 원소는 소문자 알파벳으로 이루어져 있습니다.
strings의 원소는 길이 1 이상, 100이하인 문자열입니다.
모든 strings의 원소의 길이는 n보다 큽니다.
인덱스 1의 문자가 같은 문자열이 여럿 일 경우, 사전순으로 앞선 문자열이 앞쪽에 위치합니다.
strings | n | return |
---|---|---|
["sun", "bed", "car"] | 1 | ["car", "bed", "sun"] |
["abce", "abcd", "cdx"] | 2 | ["abcd", "abce", "cdx"] |
"sun", "bed", "car"의 1번째 인덱스 값은 각각 "u", "e", "a" 입니다. 이를 기준으로 strings를 정렬하면 ["car", "bed", "sun"] 입니다.
"abce"와 "abcd", "cdx"의 2번째 인덱스 값은 "c", "c", "x"입니다. 따라서 정렬 후에는 "cdx"가 가장 뒤에 위치합니다. "abce"와 "abcd"는 사전순으로 정렬하면 "abcd"가 우선하므로, 답은 ["abcd", "abce", "cdx"] 입니다.
class Solution {
public String[] solution(String[] strings, int n) {
String[] answer = {};
int len=strings.length;
for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
if(strings[i].charAt(n)>=strings[j].charAt(n)){//sun과 bed
if(strings[i].charAt(n)==strings[j].charAt(n)){
//c와 c로 같다
if(strings[i].compareTo(strings[j])>0){
//abce와 abcd
String temp=strings[i];
strings[i]=strings[j];
strings[j]=temp;
}
}
else{
String temp=strings[i];
strings[i]=strings[j];
strings[j]=temp;
}
}
}
}
answer=strings;
return answer;
}
}
앞에 있는 것이 뒤에것보다 뒤로 정렬되어야 할 때만 정렬을 시작하면 된다.