[LeetCode] 443. String Compression(Kotlin)

0

LeetCode

목록 보기
58/58
post-thumbnail

[LeetCode] 443. String Compression(Kotlin)

풀이

class Solution {
    fun compress(chars: CharArray): Int {
        // 1. compress char array to string
        val compressedChars = StringBuilder()
        var cnt = 1
        for(i in 0 until chars.size-1){
            if(chars[i] == chars[i+1]){
                cnt++
            }
            else{
                compressedChars.append(chars[i])
                if(cnt > 1) compressedChars.append(cnt.toString())
                cnt = 1
            }
        }
        compressedChars.append(chars.last())
        if(cnt > 1) compressedChars.append(cnt.toString())

        // 2. modify input array
        compressedChars.forEachIndexed{index, ch ->
            chars[index] = ch
        }
        return compressedChars.toString().length
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글