forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
39 lines (32 loc) ยท 1.35 KB
/
jdalma.kt
File metadata and controls
39 lines (32 loc) ยท 1.35 KB
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
package leetcode_study
import io.kotest.matchers.equals.shouldBeEqual
import org.junit.jupiter.api.Test
/**
* ์ธ์ฝ๋ฉ๊ณผ ๋์ฝ๋ฉ์ ํด๊ฒฐํ ๋ ๊ตฌ๋ถ์๋ฅผ 256๊ฐ์ ASCII ๋ฌธ์ ์ค ํ๋๋ฅผ ์ฌ์ฉํด์ผํ๋ค๋ฉด ์๋์ ๊ฐ์ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ ์ ์๋ค.
* ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(1)
*/
class `encode-and-decode-strings` {
private val DELIMITER = ":"
fun encode(strings: List<String>): String {
return strings.joinToString(separator = "") { e -> "${e.length}$DELIMITER$e" }
}
fun decode(string: String): List<String> {
var index = 0
val result = mutableListOf<String>()
while (index < string.length) {
val delimiterIndex = string.indexOf(DELIMITER, startIndex = index)
val size = string.substring(index, delimiterIndex).toInt()
result.add(string.substring(delimiterIndex + 1, delimiterIndex + size + 1))
index = delimiterIndex + size + 1
}
return result
}
@Test
fun `๋ฌธ์์ด ๋ชฉ๋ก์ ํ๋์ ๋ฌธ์์ด๋ก ์ธ์ฝ๋ฉํ๋ค`() {
encode(listOf("leet","co:de","l:o:v:e","you")) shouldBeEqual "4:leet5:co:de7:l:o:v:e3:you"
}
@Test
fun `๋ฌธ์์ด์ ๋ฌธ์์ด ๋ชฉ๋ก์ผ๋ก ๋์ฝ๋ฉํ๋ค`() {
decode("4:leet5:co:de7:l:o:v:e3:you") shouldBeEqual listOf("leet","co:de","l:o:v:e","you")
}
}