[프로그래머스] 레벨 2 : 튜플

문제 보기

소스

kotlin

나의 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
fun solution(s: String): IntArray {
val set = mutableSetOf<Int>()
val elements = s.replace("{{", "").replace("}}", "").split("},{")
val arr = elements.map { it.split(",") }.sortedBy { it.size }

arr.forEach {
it.forEach {
set.add(it.toInt())
}
}

return set.toIntArray()
}
}

fold(…) 사용

1
2
3
4
5
6
7
8
9
class Solution {
fun solution(s: String): IntArray {
return s.split("},{")
.map { it.replace("[^0-9,]".toRegex(), "").split(",").map { it.toInt() } }
.sortedBy { it.size }
.fold(setOf<Int>()) { acc, list -> acc.union(list) }
.toIntArray()
}
}

댓글