SW Test/Programmers

[Programmers] Lv2. ๋ฉ”๋‰ด ๋ฆฌ๋‰ด์–ผ(kotlin)

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

๋ฌธ์ œ

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

 

 

 

์˜ˆ์‹œ

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

 

 

ํ’€์ด

  • ํ•˜๋‚˜์˜ ์ฃผ๋ฌธ(order)์—์„œ ๊ตฌ์„ฑ๋  ์ˆ˜ ์žˆ๋Š” ๋ฉ”๋‰ด ๊ตฌ์„ฑ์„ ๋ฐฑํŠธ๋ž˜ํ‚น ๊ธฐ๋ฒ•์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด ๋•Œ ์ตœ์†Œ 2๊ฐœ ์ด์ƒ์˜ ๋ฉ”๋‰ด๊ฐ€ ๊ตฌ์„ฑ๋˜์–ด์•ผ ํ•˜๊ธฐ์— ๋ฌธ์ž์—ด์ด 2 ์ดํ•˜์ธ ๊ฒฝ์šฐ๋Š” ์ œ์™ธํ•˜๊ณ  ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋กœ ํ‘œํ˜„ํ•ด์•ผํ•˜๊ธฐ์— ๋ฏธ๋ฆฌ ์ •๋ ฌ์„ ์‹œํ‚ต๋‹ˆ๋‹ค.
  • ์ดํ›„ course ๋ฅผ ํ•˜๋‚˜์”ฉ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ํ•ด๋‹น ๊ฐฏ์ˆ˜๋กœ ๊ตฌ์„ฑ๋œ ๋ฉ”๋‰ด ์กฐํ•ฉ ์ค‘ 2๋ฒˆ ์ด์ƒ ์ฃผ๋ฌธ๋œ  ๊ฒƒ ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ตœ๋Œ“๊ฐ’๊ณผ ๋™์ผํ•œ ๋ฉ”๋‰ด ๊ตฌ์„ฑ์„ ๋ชจ๋‘ answer์— ์ถ”๊ฐ€ํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
class Solution {
    val csmap = mutableMapOf<String, Int>()
    
    fun getCourseInfo(str: String, idx: Int, s: String){
        if(str.length == idx){
            if(s.length >= 2){
                csmap.put(s, csmap.getOrDefault(s, 0) + 1)
            }
        }else{
            getCourseInfo(str, idx+1, s+str[idx])
            getCourseInfo(str, idx+1, s)
        }
    }
    
    fun solution(orders: Array<String>, course: IntArray): Array<String> {  
        val answer = mutableListOf<String>()
        orders.forEach{
            val str = it.toCharArray().sorted().joinToString("")
            getCourseInfo(str, 0, "")
        }
        
        course.forEach{ cnt ->
            val max = csmap.filter{it.key.length == cnt && it.value >= 2}.values.maxOrNull()
            max?.let{ max ->
                answer.addAll(csmap.filter{it.key.length == cnt}.filter{it.value == max}.keys)
            }
        }

        return answer.sorted().toTypedArray()
    }
}

 

 

 

์ฐธ๊ณ 

 

maxOrNull - Kotlin Programming Language

 

kotlinlang.org

 

๋ฐ˜์‘ํ˜•