SW Test/Programmers

[Programmers] Lv2. ๋ฌธ์ž์—ด ์••์ถ•(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 7. 28. 23:08
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/60057?language=kotlin

 

 

์˜ˆ์‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/60057?language=kotlin

 

 

 

ํ’€์ด

  • ์˜ˆ์‹œ 5๋ฅผ ๋ณด์—ฌ์ฃผ์ง„ ๋ชปํ–ˆ์ง€๋งŒ, ๋ฌธ์ œ์—์„œ ํ™•์ธํ•ด๋ณด๋ฉด ๋ฌธ์ž์—ด์€ ๋ฌด์กฐ๊ฑด ์ฒ˜์Œ๋ถ€ํ„ฐ ์ •ํ•ด์ง„ ๊ธธ์ด๋กœ ์ž๋ฅธ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ๋ฌธ์ž์—ด์ด ๊ธธ์ด๊ฐ€ 1์ธ ๊ฒฝ์šฐ๋Š” 1๋ณด๋‹ค ์งง์€ ๋ฌธ์ž์—ด์€ ์—†๊ธฐ ๋•Œ๋ฌธ์— 1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
  • ๊ทธ๋ฆฌ๊ณ  ๋ฌธ์ž์—ด ๊ธธ์ด์˜ ์ ˆ๋ฐ˜ ์ดˆ๊ณผ์˜ ๊ธธ์ด์ผ ๊ฒฝ์šฐ ์••์ถ•์„ ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.๋”ฐ๋ผ์„œ ๋ฌธ์ž์—ด ๊ธธ์ด ์ ˆ๋ฐ˜ ์ดํ•˜์˜ ๊ธธ์ด๋กœ ์••์ถ•ํ•ด์„œ ์ตœ์†Œํ•œ์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
  • count ๋ณ€์ˆ˜๋Š” ์‹œ์ž‘ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์™€ ํ•ด๋‹น ๊ธธ์ด๋กœ ์••์ถ• ์‹œ ํ•ด๋‹น ๊ธธ์ด๋ณด๋‹ค ์ž‘์€ ๋ถ€๋ถ„์„ ๋ณ„๋„๋กœ ๋”ํ•ด์ค๋‹ˆ๋‹ค. ์ฆ‰, 8์˜ ๊ธธ์ด๋ฅผ ๊ฐ€์ง€๋Š” ๋ฌธ์ž์—ด์—์„œ 3๊ฐœ์”ฉ ์ชผ๊ฐœ์„œ ์••์ถ•ํ•  ๊ฒฝ์šฐ ๋‚˜๋จธ์ง€ 2๋Š” ์ž๋™์œผ๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.
  • str์— ๋ฌธ์ž์—ด์„ ์ €์žฅํ•ด๋‘๊ณ  ๋‹ค์Œ ๋ฌธ์ž์—ด๊ณผ ๊ฐ™์œผ๋ฉด cnt๋ฅผ +1 ํ•ด์ฃผ๊ณ  ๋‹ค๋ฅด๋ฉด cnt๊ฐ€ ์ฐจ์ง€ํ•˜๋Š” ๋งŒํผ ์ถ”๊ฐ€๋กœ ๋”ํ•ด์ค๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ฃผ์˜์ ์€ cnt๊ฐ€ 10์ผ ๊ฒฝ์šฐ๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด๊ฐ€ +2, cnt๊ฐ€ 100์ผ ๊ฒฝ์šฐ๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด๊ฐ€ +3์ด ๋œ๋‹ค๋Š” ์ ์ž…๋‹ˆ๋‹ค. 
import kotlin.math.*

class Solution {
    fun solution(s: String): Int {
        var answer = 1000
        if(s.length == 1) return 1
        
        (1..s.length/2).forEach{
            var count = it + (s.length % it)
            var str = s.substring(0,it)
            
            var cnt = 1
            for(i in it..(s.length - it) step it){
                if(str == s.substring(i, i+it)){
                    cnt++
                }else{
                    str = s.substring(i, i+it)
                    count+=it
                    count+= if(cnt == 1) 0 else cnt.toString().length
                    cnt = 1
                }
            }
            
            count+= if(cnt == 1) 0 else cnt.toString().length
            answer = min(count, answer)
        }
        return answer
    }
}

 

 

 

์ฐธ๊ณ 

 

substring - Kotlin Programming Language

 

kotlinlang.org

 

๋ฐ˜์‘ํ˜•