728x90
문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
입력
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
출력
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.
나의 접근방법
동일한 문자열이 들어오는 것을 없애주기 위해서 Set 자료구조를 사용했다. 그리고 먼저 사전순서로 정렬을 해놓고 문자열 길이를 비교하기 위해서 sorted() 함수를 사용했다.
코드
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.math.min
fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
val count = readLine().toInt()
val set = mutableSetOf<String>().apply {
repeat(count) {
this.add(readLine())
}
}
repeat(count) {
if (set.isEmpty()){ return@with }
val sortedList = set.sorted()
var minLength = 0
sortedList.forEachIndexed { index, item ->
val tmp = min(sortedList[minLength].length, item.length)
if (sortedList[minLength].length != tmp) {
minLength = index
}
}
println(sortedList[minLength])
set.remove(sortedList[minLength])
}
}
IDE에서는 결과가 제대로 나와서 제출했지만 시간초과가 떴다...ㅠㅠㅠ 그래서 코드를 좀 더 수정해보았다.
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
val count = readLine().toInt()
val set = mutableSetOf<String>().apply {
repeat(count) {
this.add(readLine())
}
}
repeat(count) {
if (set.isEmpty()){ return@with }
val sortedList = set.sorted()
val min = sortedList.minByOrNull { it.length }!!
println(min)
set.remove(min)
}
}
열심히 구글링해가면서 열심히 줄였는데 이번에도 시간초과가 났다... 후...ㅠㅠ
그래서 다른 분들의 코드를 살펴보았다.
다른 분의 접근방법
import java.io.BufferedReader
import java.io.InputStreamReader
fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
val n = readLine().toInt()
val set: MutableSet<String> = mutableSetOf()
repeat(n) {
set.add(readLine())
}
val list = set.sortedWith(Comparator<String> { a, b ->
if (a.length > b.length) 1
else if (a.length < b.length) -1
else a.compareTo(b)
})
list.forEach { println(it) }
}
이 코드를 보면서 Comparator
에 대해 처음 알게 되었다. 지금까지 C언어에서 Selection Sort할 때처럼 했었는데 완전 혁명이었다. 나중에 Comparator
에 대해 자세히 정리해봐야겠다.
728x90
'Algorithm > 백준 알고리즘' 카테고리의 다른 글
BOJ(2609) - Kotlin (0) | 2022.06.07 |
---|---|
BOJ(1436) - Kotlin (0) | 2022.06.03 |
BOJ(11050) - Kotlin (0) | 2022.05.31 |
BOJ(1008) - Kotlin (0) | 2022.05.29 |
BOJ(2869) - Kotlin (0) | 2022.05.28 |