Algorithm
[프로그래머스]문자열 내 마음대로 정렬하기
09297
2020. 9. 11. 22:43
1. Arrays.sort()와 Collections.sort()를 사용할 줄 알아야 함.
2. Comparable과 Comparator의 차이 알기
Comparable : 객체 간의 일반적인 정렬이 필요할 때, Comparable 인터페이스를 확장해서 정렬의 기준을 정의하는 compareTo() 메서드를 구현한다.
Comparator : 객체 간의 특정한 정렬이 필요할 때, Comparator 인터페이스를 확장해서 특정 기준을 정의하는 compare() 메서드를 구현한다.
package OneDayOneCodingChallenge;
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.Comparator;
import org.junit.Test;
/**
* @author seoyeon on 2020/09/11
* @project AlgorithmTest
*/
public class Day8 {
public String[] solution(String[] strings, int n) {
Arrays.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
char c1 = s1.charAt(n);
char c2 = s2.charAt(n);
// n번째 문자가 같을 경우에 원본 스트링을 사전순으로
if (c1 == c2) {
return s1.compareTo(s2); // 오름차순
} else {
return c1 - c2; // 오름차순
}
}
});
return strings;
}
@Test
public void 정답() {
assertArrayEquals(new String[]{"abcd", "abce", "cdx"},
solution(new String[]{"abce", "abcd", "cdx"}, 2));
}
}