Skip to content

Commit 5f10498

Browse files
authored
443. String Compression
1 parent f2292b1 commit 5f10498

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

443.StringCompression.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
fun compress(chars: CharArray): Int {
3+
var index = 0
4+
var count = 1
5+
6+
for (i in 1 until chars.size) {
7+
if (chars[i] == chars[i - 1]) {
8+
count++
9+
} else {
10+
chars[index++] = chars[i - 1]
11+
if (count > 1) {
12+
for (c in count.toString()) {
13+
chars[index++] = c
14+
}
15+
}
16+
count = 1
17+
}
18+
}
19+
20+
chars[index++] = chars[chars.size - 1]
21+
if (count > 1) {
22+
for (c in count.toString()) {
23+
chars[index++] = c
24+
}
25+
}
26+
27+
return index
28+
}
29+
}

0 commit comments

Comments
 (0)