Skip to content

Commit 06e13be

Browse files
authored
Merge pull request #2014 from Zhaoshan-Duan/encode-and-decode-strings
Create: 0217-encode-and-decode-strings.kt
2 parents 50a6c68 + 25333d5 commit 06e13be

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Codec {
2+
// Encodes a list of strings to a single string.
3+
fun encode(strs: List<String>): String {
4+
var res = ""
5+
strs.forEach{
6+
res = res + it.length + "#" + it
7+
}
8+
return res
9+
}
10+
11+
// Decodes a single string to a list of strings.
12+
fun decode(s: String): List<String> {
13+
var (res, i) = Pair(mutableListOf<String>(), 0)
14+
15+
while (i < s.length){
16+
var j = i
17+
while (s[j] != '#') {
18+
j++
19+
}
20+
val lengthOfWord = s.subSequence(i, j).toString().toInt()
21+
22+
val (wordStart, wordEnd) = Pair(j+1, j+1+lengthOfWord)
23+
res.add(s.subSequence(wordStart, wordEnd).toString())
24+
25+
i = wordEnd
26+
27+
}
28+
return res
29+
30+
}
31+
}
32+
33+
/**
34+
* Your Codec object will be instantiated and called as such:
35+
* var obj = Codec()
36+
* val s = obj.encode(strs)
37+
* val ans = obj.decode(s)
38+
*/

0 commit comments

Comments
 (0)