#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
- string์ ์บ๋ฆญํฐ ๊ฐ์๋ .length๋ก ๊ฐ์ ธ์ฌ ์ ์๋ค.
- ์บ๋ฆญํฐ ํน์ ์๋ธ์คํธ๋ง์ด ๋ฌธ์์ด์ ๋ค์ด์๋์ง ํ์ธํ ๋ ๋ฌธ์์ด.contains("์ํ๋ ๋ถ๋ถ")์ ์ฌ์ฉํด์ ์๋์ง ์๋์ง ํ์ธํ ์ ์๋ค.
- ๋ฆฌ์คํธ์ด๋ฆ.indexOf(index, startIndex) ์ฌ์ฉ๊ฐ๋ฅ
- ๋ฆฌ์คํธ ์์ ๋ฆฌ์คํธ์ด๋ฆ.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
..