๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/Kotlin

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค • ์ฝ”ํ‹€๋ฆฐ] ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ฐ™์€ ๊ธ€์ž #142086

by ํ‚ค์œค 2023. 12. 6.

#142086

๐ŸŽ„ Question ?

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

class Solution {
    fun solution(s: String): IntArray {
        var answer: IntArray = intArrayOf()
        return answer
    }
}

๐Ÿงฉ Thought Process

  1. string์˜ ์บ๋ฆญํ„ฐ ๊ฐœ์ˆ˜๋Š” .length๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
  2. ์บ๋ฆญํ„ฐ ํ˜น์€ ์„œ๋ธŒ์ŠคํŠธ๋ง์ด ๋ฌธ์ž์—ด์— ๋“ค์–ด์žˆ๋Š”์ง€ ํ™•์ธํ•  ๋•Œ ๋ฌธ์ž์—ด.contains("์›ํ•˜๋Š” ๋ถ€๋ถ„")์„ ์‚ฌ์šฉํ•ด์„œ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.
  3. ๋ฆฌ์ŠคํŠธ์ด๋ฆ„.indexOf(index, startIndex) ์‚ฌ์šฉ๊ฐ€๋Šฅ
  4. ๋ฆฌ์ŠคํŠธ ์ˆ˜์ • ๋ฆฌ์ŠคํŠธ์ด๋ฆ„.set(์ธ๋ฑ์Šค, ๋งค๊ฐœ๋ณ€์ˆ˜)
class Solution {
    fun solution(s: String): IntArray {
        var chars = mutableSetOf<Char>()
        var indexList = mutableListOf<Int>()
        var answer = mutableListOf<Int>(s.length)
        for (i in 0 until s.length) {
            if (chars.contains(s[i]) != true) {
                chars.add(s[i])
                var lastIndex = i
                indexList.add(lastIndex)
                while (lastIndex != -1) {
                    indexList.add(s.indexOf(s[i], lastIndex+1))
                }
            } else {break}
            for (k in indexList.indices) {
                when (k) {
                    0 -> answer.set(k, -1)
                    else -> answer.set(k, indexList[k]-indexList[k-1])
                }
            }
            indexList.clear()
        }
        return answer.toIntArray()
    }
}
//str.indexOf(searchStr, startIndex=5)
//MutableList.set(index, element)

๐ŸŽ€ Answer

ํ•œ์ฐธ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ๊ฒฐ๊ตญ ์ฐพ์•„๋ดค๋‹ค. hashMap์„ ์‚ฌ์šฉํ–ˆ๋‹ค. hashMap๋„ ๊ณต๋ถ€ํ•ด์•ผ๋œ๋‹ค...

class NearestSameLetter {
    fun solution(s: String): IntArray {
        val prevIndexMap = hashMapOf<Char, Int>()
        return s.mapIndexed { index, c ->
            val prevIndex = prevIndexMap[c]
            prevIndexMap[c] = index
            if (prevIndex == null) -1 else index - prevIndex
        }.toIntArray()
    }
}

๐ŸŽ Result

..

๐Ÿ† Comment