Advertisement
sanya5791

String Compressor fixed

Aug 15th, 2021
1,470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.72 KB | None | 0 0
  1. class Compressor {
  2.  
  3.     fun compress(s: String): String {
  4.         if(s.isEmpty()) return s
  5.  
  6.         val b = StringBuilder()
  7.         var cnt = 0
  8.         var rChar: Char = s[0]
  9.         for(ch in s) {
  10.             if(ch == rChar) {
  11.                 cnt++
  12.             } else {
  13.                 b.appendRepeat(cnt, rChar)
  14.  
  15.                 cnt = 1
  16.                 rChar = ch
  17.             }
  18.         }
  19.  
  20.         if(cnt == 1) {
  21.             b.append(rChar)
  22.         } else {
  23.             b.appendRepeat(cnt, rChar)
  24.         }
  25.  
  26.         return b.toString()
  27.     }
  28.  
  29.     private fun StringBuilder.appendRepeat(repeatCnt: Int, ch: Char) {
  30.         if(repeatCnt > 1) append(repeatCnt.toString())
  31.  
  32.         append(ch)
  33.     }
  34.  
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement