forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0271-encode-and-decode-strings.kt
43 lines (40 loc) · 1.33 KB
/
0271-encode-and-decode-strings.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
43
package kotlin
class Codec {
// Encodes a list of strings to a single string.
fun encode(strs: List<String>): String {
val stringBuilder = StringBuilder()
for (string in strs) {
for (char in string) {
stringBuilder.append(char.toInt()) // char.code in newer version's of Kotlin
stringBuilder.append(CHAR_DELIMITER)
}
stringBuilder.append(STRING_DELIMITER)
}
return stringBuilder.toString()
}
// Decodes a single string to a list of strings.
fun decode(s: String): List<String> {
val stringBuilder = StringBuilder()
val resultantList = mutableListOf<String>()
var i = 0
while (i in s.indices) {
while (s[i] != STRING_DELIMITER) {
var charIntegerValue = ""
while (s[i] != CHAR_DELIMITER) {
charIntegerValue += s[i]
i++
}
stringBuilder.append(charIntegerValue.toInt().toChar())
i++
}
resultantList.add(stringBuilder.toString())
stringBuilder.clear()
i++
}
return resultantList
}
companion object {
private const val CHAR_DELIMITER = '|'
private const val STRING_DELIMITER = '/'
}
}