Skip to content

Commit

Permalink
add Kotlin solution for problem neetcode-gh#271
Browse files Browse the repository at this point in the history
  • Loading branch information
technophilist committed Jun 9, 2023
1 parent 9d668c6 commit 9c26a64
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions kotlin/0271-encode-and-decode-strings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,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 = '/'
}
}

0 comments on commit 9c26a64

Please sign in to comment.