From 9c26a645a7a91cd50817b33090161dbe70470dce Mon Sep 17 00:00:00 2001 From: t3chkid <54663474+t3chkid@users.noreply.github.com> Date: Fri, 9 Jun 2023 09:01:36 +0530 Subject: [PATCH] add Kotlin solution for problem #271 --- kotlin/0271-encode-and-decode-strings.kt | 43 ++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 kotlin/0271-encode-and-decode-strings.kt diff --git a/kotlin/0271-encode-and-decode-strings.kt b/kotlin/0271-encode-and-decode-strings.kt new file mode 100644 index 000000000..fdabb89de --- /dev/null +++ b/kotlin/0271-encode-and-decode-strings.kt @@ -0,0 +1,43 @@ +package kotlin + +class Codec { + // Encodes a list of strings to a single string. + fun encode(strs: List): 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 { + val stringBuilder = StringBuilder() + val resultantList = mutableListOf() + 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 = '/' + } +} \ No newline at end of file