Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Compressor {
- fun compress(s: String): String {
- val b = StringBuilder()
- var cnt = 0
- var rChar: Char = s[0]
- for(ch in s) {
- if(cnt == 0) {
- rChar = ch
- }
- if(ch == rChar) {
- cnt++
- } else {
- b.appendRepeat(cnt, rChar)
- cnt = 1
- rChar = ch
- }
- }
- if(cnt == 1) {
- b.append(rChar)
- } else {
- b.appendRepeat(cnt, rChar)
- }
- return b.toString()
- }
- private fun StringBuilder.appendRepeat(repeatCnt: Int, ch: Char) {
- append(repeatCnt.toString())
- append(ch)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement