---
# System prepended metadata

title: 0443. String Compression
tags: [Leetcode, FaceBook, Two Pointers, Medium, Microsoft]

---

# 0443. String Compression
###### tags: `Leetcode` `Microsoft` `Medium` `Two Pointers` `FaceBook`
Link: https://leetcode.com/problems/string-compression/
## 思路
简单的双指针就可以解啦
非常巧妙的一点是如果count>10，要把一位一位拆开存进去
这里的方式是先把count转成string，然后一位一位存进去
## Code
```java=
class Solution {
    public int compress(char[] chars) {
        char prev = chars[0];
        int count = 1;
        int idx = 1;
        for(int i = 1;i < chars.length;i++){
            if(chars[i] == prev){
                count++;
            }
            else{
                if (count != 1) {
                    prev = chars[i];
                    String s = Integer.toString(count);
                    for(int j = 0;j < s.length();j++){
                        chars[idx++] = Integer.toString(count).charAt(j);
                    }
                    chars[idx++] = chars[i];
                    count = 1;
                }
                else{
                    prev = chars[i];
                    chars[idx++] = chars[i];
                }
            }
        }
        if(count != 1){
            String s = Integer.toString(count);
            for(int j = 0;j < s.length();j++){
                chars[idx++] = Integer.toString(count).charAt(j);
            }
        }
        return idx;
    }
}
```