- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0916-decoded-string-at-index.kt
42 lines (36 loc) · 1.4 KB
/
0916-decoded-string-at-index.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
classSolution {
fundecodeAtIndex(s:String, k:Int): String {
val string =if (s.last().isLetter()) s +"2"else s
val intervalSizes =mutableListOf(0L)
val coefficients =mutableListOf(0L)
val tokens =mutableListOf("")
var isDigitBefore =false
var nextB =1L
val accumulated = mutableListOf<Char>()
for (char in string) {
if (char.isDigit() != isDigitBefore) {
if (!isDigitBefore) {
tokens.add(accumulated.joinToString(""))
coefficients.add(nextB)
intervalSizes.add(intervalSizes.last() * nextB + accumulated.size)
} else {
nextB = accumulated.fold(1L) { acc:Long, c:Char-> acc * c.digitToInt() }
}
isDigitBefore =!isDigitBefore
accumulated.clear()
}
accumulated.add(char)
}
var remainder = k -1L
var current = intervalSizes.size -1
while (current >0) {
remainder %= intervalSizes[current]
val additionalPartStartsAt = intervalSizes[current -1] * coefficients[current]
if (remainder >= additionalPartStartsAt) {
return tokens[current][(remainder - additionalPartStartsAt).toInt()].toString()
}
--current
}
return""
}
}