---
# System prepended metadata

title: 443. String Compression
tags: [String]

---

---
title: 443. String Compression
tags: String
description: share source code.
---

# 443. String Compression

```java

class Solution {
    public int compress(char[] chars) {
        int n = chars.length;
        char last = chars[0];
        
        List<String> list = new ArrayList<>();
        
        int cnt = 1;
        for(int i = 1; i < n; i++ ){
             if(last == chars[i]){
                 cnt++;
             }else{
                 list.add(last+"");
                 if(cnt > 1){
                     list.add(cnt +"");
                 }
                 
                 last = chars[i];
                 cnt = 1;
             }
        }
        
        list.add(last +"");
        if(cnt > 1){
           list.add(cnt +"");
         }

            
        String str = String.join("", list);
        for(int i = 0; i < str.length(); i++){
            chars[i] = str.charAt(i);
        }
        
        return str.length();
    }
}

