SW Test/Programmers

[Programmers] Lv2. ํŠœํ”Œ(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 9. 24. 21:13
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/64065

 

 

 

์˜ˆ์‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/64065

 

 

ํ’€์ด

  • ์œ„ ๋ฌธ์ œ๋Š” ๋ฌธ์ž์—ด๋กœ ์ฃผ์–ด์ง€๋Š” ์ž…๋ ฅ๊ฐ’์„ 2์ค‘ ๋ฆฌ์ŠคํŠธ๋กœ๋งŒ ๋ณ€๊ฒฝํ•˜๋ฉด ์‰ฌ์šด ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
  • ์ €๋Š” split์„ ํ•˜๋Š” ๊ธฐ์ค€์„ "},"๋กœ ์žก์•˜๊ณ  ์ดํ›„ ๊ฐ ๋ฌธ์ž์—ด์—์„œ '{'์™€ '}'๋Š” ๋นˆ ๊ณต๊ฐ„์œผ๋กœ ๋ณ€๊ฒฝํ•˜์˜€์Šต๋‹ˆ๋‹ค.
  • ํŠœํ”Œ์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋ฆฌ์ŠคํŠธ ๋‚ด ๋ฆฌ์ŠคํŠธ ์›์†Œ ๊ฐฏ์ˆ˜๊ฐ€ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ์„ ์‹œ์ผœ์•ผ ์˜ฌ๋ฐ”๋ฅธ ๋‹ต์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ์ดํ›„ ์ค‘๋ณต์ด ๋˜์ง€ ์•Š๋„๋ก answer ๋ฆฌ์ŠคํŠธ์— ๋”ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ํ•˜๋‚˜์”ฉ ํ•ด๋„ ๋˜์ง€๋งŒ fold ํ•จ์ˆ˜์™€ set์˜ ํŠน์ง•์„ ์‚ฌ์šฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
class Solution {
    fun solution(s: String): IntArray {
        var answer = mutableListOf<Int>()
        val list = s.split("},").map{
            it.replace('{',' ').replace('}',' ').trim().split(",").map{it.toInt()}.sorted()
        }.sortedBy{it.size}
        
        list.forEach{ sublist ->
            sublist.forEach{
                if(!answer.contains(it)){
                    answer.add(it)
                }
            }
        }
        
        return answer.toIntArray()
    }
}

 

 

 

์ฐธ๊ณ 

  • ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์ธ kotlin์˜ ํŠน์„ฑ์— ๋งž๊ฒŒ ํ•จ์ˆ˜๋ฅผ ๋งŽ์ด ์ตํžˆ์ž ๐Ÿ˜ฝ
  • mutableListOf๋Š” java์˜ ArrayList๋ฅผ ์ƒ์„ฑํ•ด์ฃผ๊ณ  java์˜ ArrayList๋Š” ์‚ฌ์ด์ฆˆ๋ฅผ ์กฐ์ ˆ ๊ฐ€๋Šฅํ•œ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค. ์ดˆ๊ธฐ ์„ค์ •ํ•œ ๋ฐฐ์—ด์˜ capacity๋ณด๋‹ค ์ถ”๊ฐ€๋ฅผ ํ•ด์•ผํ•  ๊ฒฝ์šฐ ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๋Š” ์ž‘์—…์„ ์ž๋™์œผ๋กœ ํ•ด์ฃผ๊ฒŒ ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.
  • mutablesetOf๋Š” java์˜ LinkedHashSet์„ ์ƒ์„ฑํ•˜์—ฌ ํ•ด์‰ฌํ…Œ์ด๋ธ”๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๋ฆฌํ•˜๊ณ  ์ถ”๊ฐ€์ ์œผ๋กœ Double Linked List๋กœ ์ˆœ์„œ๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค.
  • https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/fold.html
 

fold - Kotlin Programming Language

 

kotlinlang.org

 

๋ฐ˜์‘ํ˜•