# 443. String Compression

{% embed url="<https://leetcode.com/problems/string-compression/>" %}

对`Array`做同步的读写，试试双指针，字符变化的时候即需要执行写入操作。

{% tabs %}
{% tab title="双指针" %}

```python
class Solution:
    def compress(self, chars: List[str]) -> int:
        # 字符、写入双指针
        read, write = 0, 0
        count = 0
        
        for n in range(len(chars)+1):
            if n < len(chars):
                ch = chars[n] # 如果是同样的字符，就计数+1
                if chars[n] == chars[read]: count += 1
            
            # 遇到不一样的字符
            if ch != chars[read] or n == len(chars):
                # 在 write 指针位置写入，然后移动一位准备写入计数
                chars[write] = chars[read]
                write += 1
                
                # 如果计数小于等于1，则不需要写入
                if count > 1:
                    count = str(count)
                    for i in range(len(count)):
                        chars[write] = count[i]
                        write += 1
                        # 用来写入计数的位数，永远不回多于实际的字符位数 
                
                # 重置字符到当前位置
                read = n
                count = 1
                
        return write
```

{% endtab %}

{% tab title="pop/insert" %}

```python
class Solution:
    def compress(self, chars: List[str]) -> int:
        count = 1
        for i in range(len(chars)-1,-1,-1):
            # 遇到相同字符就计数，并且把它pop掉
            if i and chars[i]==chars[i-1]:
                count += 1
                chars.pop(i)
            # 遇到不同的，就写入计数
            else:
                if count > 1:
                    for item in str(count)[::-1]: 
                        chars.insert(i+1, item)
                    count = 1
```

{% endtab %}
{% endtabs %}
